Node.js Reference ยท path, os and url
Node.js path.matchesGlob() method
Reference for path.matchesGlob() in Node.js: test one path against a glob pattern with *, ** and braces, without touching the disk, and how it relates to fs.glob().
path.matchesGlob(path, pattern) answers a yes-or-no question: does this path match this glob pattern? Patterns use the familiar shell-style symbols: * for "any characters inside one segment", ** for "any number of folders", ? for one character, and braces such as {js,ts} for alternatives.
It only compares strings. To list the files that match a pattern on disk, use fs.glob().
import path from "node:path"; path.matchesGlob("src/app/main.js", "src/**/*.js"); // true
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Syntax
path.matchesGlob(path, pattern): boolean
| Name | Description |
|---|---|
path |
The path to test. |
pattern |
The glob pattern. |
Returns: true if the whole path matches, otherwise false.
Errors: ERR_INVALID_ARG_TYPE if either argument is not a string.
Usage notes
- Whole-path match. The pattern must cover the entire string, not just a part of it.
*.jsdoes not matchsrc/main.jsbecause*stops at a separator. *stays in one segment,**crosses folders.src/**/*.jsmatches files at any depth undersrc, including directly in it.- No disk access. The path does not need to exist, and no directory is read. That is why it suits filtering lists you already have, such as changed file names from a version-control tool.
- Separators. Write patterns with
/. Usepath.posix.matchesGloborpath.win32.matchesGlobto choose the platform rules explicitly, and normalize Windows paths to/first if you are unsure how a pattern is read. - Relative paths stay relative. The path is not resolved against the working directory. Normalize both sides the same way before comparing.
- Dot files are not matched by
*or**, as in most shells:*does not match.envanda/**does not matcha/.git/x. Start the pattern with a dot (.*) to match them. - Status: it was added in Node 22 and 20.17 and is marked experimental, so a version may print an experimental warning or change slightly. Pin your Node version when you rely on the edge cases.
- Not a regular expression. Characters like
+and(are literal unless they are part of glob syntax. UseRegExpwhen you need regex power.