Match paths using .gitignore syntax.
Use pathmask to filter files by including or excluding matching paths.
npm install pathmaskRequires Node.js 20 or newer. ESM only.
Create a mask from patterns and test each path with matches().
import { PathMask } from 'pathmask';
const mask = new PathMask([
'src/**/*.js',
'docs/',
'*.md',
'!CHANGELOG.md',
]);
mask.matches('src/index.js'); // true
mask.matches('src/cli/run.js'); // true
mask.matches('test/index.js'); // false
mask.matches('docs/logo.png'); // true
mask.matches('local/logo.png'); // false
mask.matches('README.md'); // true
mask.matches('test/README.md'); // true
mask.matches('CHANGELOG.md'); // falseTools often get a list of paths from a config and need to filter it, for example to choose which files to build, lint or deploy.
The .gitignore syntax is the format every developer already knows for such rules.
It is based on the basic POSIX glob syntax with *, ? and [...], and adds a few simple rules for lists of paths.
pathmask tests a given path against these rules and follows the behavior of git, so a pattern means the same here and in .gitignore.
- Short rules: a pattern without
/matches at any depth,dist/matches a directory with all its contents. - Exceptions: patterns are applied in order,
!brings a path back. - Dotfiles:
*matches names that start with., no options needed. - One reference: git defines the behavior, there are no library-specific options.
For common rules, the .gitignore syntax is shorter and easier to read than glob.
| glob | pathmask |
|---|---|
['**/node_modules/**', '**/*.log'] |
['node_modules/', '*.log'] |
['**/*.log', '!**/keep.log'] |
['*.log', '!keep.log'] |
['**/dist', '**/dist/**'] |
['dist/'] |
['**/.*'] with the option { dot: true } |
['.*'] |
To write glob patterns with {a,b} and extglob in pathmask, see Glob equivalents.
Creates a path matcher from an array of patterns in .gitignore syntax.
| Parameter | Type | Description |
|---|---|---|
patterns |
string[] |
Patterns in .gitignore syntax, see Patterns. |
Throws a TypeError when patterns is not an array of strings, see Errors.
Tests a relative path against the patterns.
| Parameter | Type | Description |
|---|---|---|
path |
string |
A path relative to the root, see Paths. |
Returns true if the mask matches the path or a directory that contains it. Otherwise, returns false.
Throws a TypeError when the path is invalid, see Errors.
Keep the paths that the mask does not match. Create the mask once and reuse it for all paths.
const excluded = new PathMask(['node_modules/', '*.log', '.*']);
const paths = ['README.md', 'debug.log', '.env', 'src/index.js', 'node_modules/ansis/index.js'];
const files = paths.filter((file) => !excluded.matches(file));
// ['README.md', 'src/index.js']Read the files of my-project and keep the files that the mask does not match.
import { readdirSync, statSync } from 'node:fs';
import path from 'node:path';
import { PathMask } from 'pathmask';
const rootPath = './my-project';
const excluded = new PathMask(['node_modules/', '*.log', '.*']);
const entries = readdirSync(rootPath, { recursive: true });
const files = [];
for (const file of entries) {
if (!statSync(path.join(rootPath, file)).isFile()) continue;
if (!excluded.matches(file)) {
files.push(file);
}
}
// ['README.md', 'src/index.js']Keep the paths that the mask matches. This mask matches JavaScript files in src and Markdown files in any directory.
const included = new PathMask(['src/**/*.js', '*.md']);
const paths = [
'README.md',
'docs/guide.md',
'package.json',
'src/index.js',
'src/cli/run.js',
'test/run.test.js',
];
const files = paths.filter((file) => included.matches(file));
// ['README.md', 'docs/guide.md', 'src/index.js', 'src/cli/run.js']Use /*.md to match Markdown files only in the root. This pattern matches README.md and does not match docs/guide.md.
Paths are relative to a root chosen by the caller. The root is not passed to PathMask.
Use / between path segments. A path that ends with / is a directory. Any other path is a file.
| Path | Description |
|---|---|
README.md |
a file in the root |
data/error.log |
a file in the directory data |
data/ |
the directory data |
data/log/ |
the directory log in the directory data |
A pattern that ends with / matches only directories.
Pass a directory as data/ to match it with the pattern data/.
A path must not start with / or contain empty path segments, . or ... Use path.relative() to get a relative path
and normalize its separators to /. In a path, a backslash is a normal character.
On Windows, path.relative() uses backslashes as separators. Convert them to / before calling matches().
mask.matches(file.replaceAll(path.sep, '/'));Patterns use .gitignore syntax.
| Wildcard | Matches |
|---|---|
* |
zero or more characters except /, including leading dots |
? |
one character except / |
[abc], [a-z] |
one of the characters |
[!abc], [^abc] |
one character that is not in the set |
[[:digit:]] |
one digit |
Supported character classes: alnum, alpha, blank, cntrl, digit, graph, lower, print, punct, space, upper, xdigit.
| Pattern | Matches the paths | Does not match the paths |
|---|---|---|
a |
a, c/a, c/d/a/ |
ab, c/a.txt |
/a |
a, a/ |
c/a |
a/b |
a/b, a/b/ |
c/a/b |
a/ |
a/, c/a/ |
a, c/a |
**/a/b |
a/b, c/a/b, c/d/a/b |
a/c/b |
a/** |
a/c, a/c/d |
a/, a |
a/**/b |
a/b, a/c/b, a/c/d/b |
b, c/a/b |
*.log |
a.log, c/a.log, c/d/a.log |
a.txt |
/*.log |
a.log |
c/a.log |
a/*.log |
a/b.log |
b.log, a/c/b.log |
a/**/*.log |
a/b.log, a/c/b.log, a/c/d/b.log |
b.log, c/a/b.log |
A / at the start or inside a pattern anchors it to the root, as in /a and a/b.
A pattern without such a / matches at any depth, as in a and a/.
Paths passed to matches() never start with /, see Paths.
A matched directory also matches all paths within it.
const mask = new PathMask(['data/']);
mask.matches('data/'); // true
mask.matches('data/log/error.log'); // trueMatching is case-sensitive.
Patterns with an unclosed character class, an unknown character class such as [[:name:]], or a trailing backslash never match.
The constructor does not throw on them.
Empty strings, strings that start with #, and a single ! are ignored.
Spaces at the end of a pattern are removed. To keep a space at the end, escape it with \, see Escaping.
const mask = new PathMask(['# logs', '*.log', '', 'tmp/']);Patterns are applied in array order. The last matching pattern determines the result for a path.
A pattern prefixed with ! negates a previous match.
const mask = new PathMask(['*.log', '!keep.log']);
mask.matches('error.log'); // true
mask.matches('keep.log'); // falseNegation cannot override a matched parent directory.
To allow exceptions within a directory, match its contents, for example data/*.
new PathMask(['data/', '!data/keep.json']).matches('data/keep.json'); // true
new PathMask(['data/*', '!data/keep.json']).matches('data/keep.json'); // falseTo exclude all paths inside a directory, negate its contents with /**, for example !drafts/**.
new PathMask(['*.md', '!drafts/']).matches('drafts/a.md'); // true
new PathMask(['*.md', '!drafts/**']).matches('drafts/a.md'); // falseA negated pattern has no effect without a previous match.
A backslash escapes the next character, so the character is matched literally.
The table shows patterns as plain text. In a JavaScript string, write \\ for one backslash.
| Pattern | Matches |
|---|---|
\!important |
the name !important |
\#notes |
the name #notes |
\*.txt |
the name *.txt |
name\ |
the name name with a space at the end |
Escape a leading ! or # to match it literally. Without escaping, a leading ! starts a negation and a leading # starts a comment.
new PathMask(['!important']).matches('!important'); // false
new PathMask(['\\!important']).matches('!important'); // trueBrace expansion and extglob patterns of glob can be written as a list of patterns, a character set or a negation.
A glob pattern always starts at the root, so a pattern without / gets a leading / to match the same paths.
| glob | pathmask |
|---|---|
*.{j,t}s |
['/*.[jt]s'] |
app.log.{1..3} |
['/app.log.[1-3]'] |
src/*.{js,json} |
['src/*.js', 'src/*.json'] |
src/*.@(ts|tsx) |
['src/*.ts', 'src/*.tsx'] |
app?(.min).js |
['/app.js', '/app.min.js'] |
src/!(*.test).js |
['src/*.js', '!src/*.test.js'] |
!(vendor)/*.js |
['*/*.js', '!vendor/*.js'] |
app.log.+([0-9]) |
['/app.log.[0-9]', '/app.log.[0-9][0-9]'], up to two digits |
app*([0-9]).log |
['/app.log', '/app[0-9].log', '/app[0-9][0-9].log'], up to two digits |
new PathMask(patterns) throws a TypeError when patterns is not an array of strings.
PathMask: patterns must be an array of strings
mask.matches(path) throws a TypeError when the path is not a string, is empty, starts with /,
or contains an empty path segment, . or ...
PathMask: path must be a relative path, got "/a"
PathMask: path must be a normalized path without empty path segments, . or .., got "a/../b"
TypeScript declarations are included in the package.
import { PathMask } from 'pathmask';
const mask: PathMask = new PathMask(['*.log']);
const matched: boolean = mask.matches('error.log');