fs.glob Matches Paths Against Patterns
Match nested files with fs.glob patterns, where one star stays inside a single path segment, two stars cross directories, and classes narrow matches.
Code
import { mkdir, writeFile, glob } from 'node:fs/promises';
await mkdir('logs/2026/11', { recursive: true });
await writeFile('logs/2026/11/app-01.log', 'level=info');
await writeFile('logs/2026/11/app-02.log', 'level=warn');
await writeFile('logs/2026/11/app-01.log.tmp', 'scratch');
await writeFile('logs/readme.md', 'how to read logs');
// glob() returns an async iterable; Array.fromAsync collects the matches
// * matches within one path segment; ** crosses directories
const logs = (await Array.fromAsync(glob('logs/**/*.log'))).sort();
console.log('log files:', logs);
const notes = (await Array.fromAsync(glob('logs/**/*.md'))).sort();
console.log('markdown:', notes);
// [0-9] is a character class, narrowing to numbered files only
const numbered = (await Array.fromAsync(glob('logs/**/app-0[12].log'))).sort();
console.log('numbered only:', numbered);Output
Captured from a sandboxed run of this snippet in the build pipeline.
log files: [ 'logs\\2026\\11\\app-01.log', 'logs\\2026\\11\\app-02.log' ]
markdown: [ 'logs\\readme.md' ]
numbered only: [ 'logs\\2026\\11\\app-01.log', 'logs\\2026\\11\\app-02.log' ]How the snippet works
The code’s whole job belongs to the functions logs, notes and numbered.
Await points sequence the asynchronous work; a rejection lands at the awaiting line. The import names the platform contact area: mkdir, writeFile, glob, all from node:fs/promises.
What to watch for
node:fs/promisesis a Node.js built-in module — it ships with the runtime, so there is nothing to install.
Applying it
Entry signature: const logs = (await Array.fromAsync(glob('logs/**/*.log')
Look for the log files:, markdown:, numbered only: prefixes when the file runs; they tie each line to its step.
Statements that matter
const numbered = (await Array.fromAsync(glob('logs/**/app-0[12].log'))).sort();
const logs = (await Array.fromAsync(glob('logs/**/*.log'))).sort();
const notes = (await Array.fromAsync(glob('logs/**/*.md'))).sort();
Interactive Tools for This Topic
Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- Do I need to install anything before running this?
- Nothing needs installing: `node:fs/promises` ships with Node.js itself.
Report a problem with this exampleOpens a pre-filled issue on GitHub.