Understanding Using Globs Node Js

Master glob patterns for efficient file matching in Node.js--from basic wildcards to the new native utilities in Node v22.17+

If you've ever used a command like git add *.js to stage multiple files at once, you've already used glob patterns. These powerful filename matching tools have been a staple of shell scripting for decades, and they've become essential in modern web development workflows. Understanding how to use globs effectively in Node.js can dramatically simplify file manipulation tasks, from organizing your project structure to configuring build processes.

In this guide, we'll explore everything you need to know about using glob patterns in Node.js, from basic syntax to advanced techniques and the exciting new native glob utilities available in recent Node.js versions.

What Are Glob Patterns

Glob patterns are strings that use wildcard characters to match filenames. The term "glob" comes from the early Unix glob command, which expanded wildcard patterns into lists of matching files. In modern development, globs serve as a concise way to specify sets of files without listing each one individually.

Why Globs Matter in Web Development

  • Used by virtually every major build tool and bundler
  • Enable configuration-as-code for file selection
  • Reduce boilerplate when working with large codebases
  • Essential for task runners, testing frameworks, and deployment pipelines

Understanding glob patterns is fundamental to modern web development practices, as they form the backbone of how tools like Next.js, Vite, and Webpack discover and process your source files. These patterns are especially valuable when working with JavaScript fundamentals that power efficient file operations.

Core Glob Pattern Syntax

Understanding the four main pattern types is essential for effective file matching in Node.js.

Single Character Wildcard (?)
1const { glob } = require('glob');2 3// ? matches exactly one character4const files = await glob('file?.txt');5// Matches: file1.txt, file2.txt, fileA.txt6// Does NOT match: file10.txt, file.txt
Multiple Character Wildcard (*)
1const { glob } = require('glob');2 3// * matches zero or more characters in one segment4const jsFiles = await glob('*.js');5// Matches: app.js, utils.js, index.js6// Does NOT match: src/app.js (crosses segment)7 8const srcTs = await glob('src/*.ts');9// Matches TypeScript files directly in src/
Recursive Matching (**)
1const { glob } = require('glob');2 3// ** matches across directory boundaries4const allJs = await glob('**/*.js');5// Matches: file.js, src/file.js, src/components/file.js6// Searches entire project recursively7 8const configs = await glob('**/*.config.{js,ts,json}');9// Matches all config files at any depth
Character Classes ([abc])
1const { glob } = require('glob');2 3// [] matches one character from the set4const files = await glob('file[12].txt');5// Matches: file1.txt, file2.txt6 7// Ranges with hyphen8const logFiles = await glob('log-[a-z]*.txt');9// Matches: log-a.txt, log-archive.txt, log-zebra.txt10 11// Negation with ^12const nonTest = await glob('src/[^test]*.ts');13// Matches TypeScript files except test files

Using the NPM Glob Package

The glob package on npm is the most widely used glob implementation for Node.js, with over 500 million weekly downloads. It provides a consistent API across all Node.js versions and offers advanced features beyond basic pattern matching. Whether you're building a Node.js backend service or configuring a frontend build system, this package delivers reliable file matching capabilities.

For projects that require broader Node.js version compatibility or need advanced pattern features like negation, the npm glob package remains an excellent choice. Its well-documented API and extensive test coverage make it a trusted solution in the development community. When combined with automated testing practices, you can ensure reliable file discovery across your test suites.

Installation
1npm install glob2# or3yarn add glob
Promise-Based API (Recommended)
1import { glob } from 'glob';2 3// Find all JavaScript files4const jsFiles = await glob('**/*.js');5 6// Find configuration files using brace expansion7const configFiles = await glob('{package.json,tsconfig.json,.eslintrc.js}');8 9// Find files with exclusion patterns10const sourceFiles = await glob('src/**/*.ts', {11 ignore: ['node_modules/**', 'dist/**', '*.config.ts']12});
Callback-Based API
1const { glob } = require('glob');2 3glob('**/*.json', (error, files) => {4 if (error) {5 console.error('Error finding files:', error);6 return;7 }8 console.log('Found JSON files:', files);9});

Native Node.js Glob Utilities (Node v22.17+)

In a significant development for the Node.js ecosystem, native glob utilities were added to Node.js core in version 22.17. This means you can now use glob patterns without installing any external packages, reducing dependency complexity and improving performance. For new projects built on modern Node.js versions, this native approach simplifies your application architecture by eliminating an external dependency while maintaining excellent performance.

The native implementation leverages Node.js's core filesystem APIs, providing tight integration with the runtime and optimized file system operations. This is particularly valuable for applications that need to process large numbers of files efficiently, such as build tools, documentation generators, and deployment scripts.

fsPromises.glob() - AsyncIterator Approach
1import { glob } from 'node:fs/promises';2 3// Iterate over discovered file paths (memory efficient)4for await (const entry of glob('**/*.txt')) {5 console.log(entry);6 // Can break early if you found what you need7 if (entry.includes('config')) break;8}9 10// Or collect all matches into an array11const allFiles = await Array.fromAsync(glob('**/*.{ts,js}'));
fs.glob() - Callback-Based
1import { glob } from 'node:fs';2 3glob('**/*.json', (error, files) => {4 if (error) {5 console.error('Error finding files:', error);6 return;7 }8 console.log('Found JSON files:', files);9});
fs.globSync() - Synchronous API
1import { globSync } from 'node:fs';2 3// Synchronous file matching for scripts4const files = globSync('src/**/*.{ts,tsx,js,jsx}');5console.log('All source files:', files);6 7// With options8const configFiles = globSync('**/*.config.{js,json}', {9 cwd: './my-project',10 ignore: 'node_modules/**'11});
Native vs npm glob package comparison
FeatureNative (Node.js v22.17+)npm glob package
DependenciesNone requiredRequires installation
Node.js version support22.17 and laterAll versions
PerformanceCore-optimizedWell-optimized
Advanced patternsStandard patternsExtended patterns
AsyncIterator supportYesVia options
Promise APIYesYes
Callback APIYesYes
Sync APIYesYes

Common Use Cases in Web Development

Build Tool Configuration

Modern build tools like Vite, Webpack, and Next.js rely on glob patterns to define entry points, include files for bundling, and specify assets that need processing. When you configure your build process, glob patterns help identify which source files to include in the bundle and how to organize the output.

Testing and Linting

Testing frameworks use globs to automatically discover test files. Jest and Vitest scan for patterns like **/*.test.{js,ts} or **/__tests__/**/*.{js,ts}. This automated discovery is essential for maintainable test suites that scale with your codebase. For TypeScript projects, understanding how globs work with Jest ensures reliable test discovery across your entire test suite.

File Organization and Cleanup

Build scripts use globs for bulk operations: generating documentation, copying assets, or cleaning build artifacts. This automation is a key part of efficient DevOps practices that reduce manual effort and ensure consistent results.

Best Practices for Performance

Optimize Your Patterns

Be specific to reduce filesystem overhead. Rather than **/*.js, use src/**/*.js when you know files are in specific directories. This targeted approach significantly improves performance in large codebases by limiting the scope of filesystem scanning.

Always Use Exclusion Patterns

Exclude directories that shouldn't be scanned: node_modules, dist, .git, and coverage. These can contain thousands of files that would significantly slow down glob operations:

const sourceFiles = await glob('src/**/*.{ts,tsx,js,jsx}', {
 ignore: ['node_modules/**', 'dist/**', '*.config.{js,ts}']
});

Choose Native for Simple Cases

For straightforward pattern matching, prefer native Node.js glob utilities. Reserve the npm glob package for advanced features or older Node.js versions. This approach keeps your dependency graph lean while leveraging the performance optimizations built into Node.js core.

Advanced Pattern Techniques

Combining Multiple Patterns

Both native and npm glob support arrays of patterns:

const files = await glob([
 'src/components/**/*.ts',
 'src/hooks/**/*.ts',
 'src/utils/**/*.ts'
]);

Dynamic Pattern Generation

Generate patterns programmatically for flexible tooling:

function getSourcePatterns(config) {
 return config.sourceDirs.map(dir => `${dir}/**/*.{${config.extensions.join(',')}}`);
}

const patterns = getSourcePatterns({
 sourceDirs: ['src', 'lib', 'packages'],
 extensions: ['ts', 'tsx', 'js', 'jsx']
});

const files = await glob(patterns);

These techniques enable dynamic build configurations that adapt to your project's evolving structure, supporting scalable architecture as your application grows. When combined with JavaScript operators like modulo, you can build sophisticated file processing pipelines.

Frequently Asked Questions

What is the difference between * and ** in glob patterns?

The single asterisk (*) matches zero or more characters within a single path segment (directory level). The double asterisk (**) matches across directory boundaries, enabling recursive matching throughout the entire directory tree.

Can I use glob patterns in Windows?

Yes, both the npm glob package and native Node.js glob utilities work on Windows. The patterns use forward slashes (/) but are automatically converted to match Windows paths with backslashes.

Is native glob available in older Node.js versions?

No, native glob utilities (fsPromises.glob, fs.glob, fs.globSync) require Node.js 22.17 or later. For older versions, use the npm glob package which supports all Node.js versions.

How do I exclude multiple directories with glob?

Use the ignore option with an array of patterns: `ignore: ['node_modules/**', 'dist/**', '.git/**']`. This prevents scanning of directories that typically don't need to be included.

Conclusion

Glob patterns are an indispensable tool in modern web development, providing a concise and powerful way to match files across your projects. With the introduction of native glob utilities in Node.js 22.17, the ecosystem has taken a significant step forward by bringing this functionality into core, reducing external dependencies while maintaining excellent performance.

Whether you're configuring build tools, writing test suites, or automating file operations, mastering glob patterns will make you a more effective developer. Start with the basic patterns--* for single-segment matching, ** for recursive matching, and ? and character classes for precise control--and gradually incorporate advanced techniques as your needs evolve.

For teams building modern web applications, understanding these patterns is just one piece of the puzzle. Our web development services can help you architect scalable solutions that leverage best practices across your entire technology stack.

Ready to Build Better Web Applications?

Our team of expert Node.js developers can help you architect scalable solutions using modern best practices.