Node.js includes a native glob utility
- Published at
- Updated at
- Reading time
- 2min
The two most popular glob utilities (minimatch and glob) are responsible for over 500 million weekly npm downloads. Something so common should be included in the Node core library, right?
Today, I discovered that native "globbing" is included in Node core since v22.17.
The new utility comes in three flavors.
This fsPromise version returns and an AsyncIterator which allows to end the globbing in a for await/of loop early if you have found what you're looking.
Alternatively, use Array if you don't care about breaking out early and want to discover all the files.
import { glob } from 'node:fs/promises';
// Iterate over discovered file paths
for await (const entry of glob('**/*.txt')) {
console.log(entry);
}
// Await all files paths
const files = await Array.fromAsync(glob('**/*.txt'));
console.log(files);
fs is callback-based if that's your jam.
import { glob } from 'node:fs';
await glob('**/*.txt', (error, files) => {
console.log(files);
});
And, of course, there's a synchronous version with fs, too.
import { globSync } from 'node:fs';
console.log(globSync('**/*.txt'));
Now, I'm sure there are some minor differences to the popular libraries, but I bet it'll be fine for some quick file-grepping in JavaScript.
Join 6.1k readers and learn something new every week with Web Weekly.
