🚀 It's a very fast and efficient glob library for Node.js
Installations
npm install fast-glob
Score
97.3
Supply Chain
99.6
Quality
75.4
Maintenance
100
Vulnerability
100
License
Developer
mrmlnc
Developer Guide
Module System
CommonJS
Min. Node Version
>=8.6.0
Typescript Support
No
Node Version
20.9.0
NPM Version
10.1.0
Statistics
2,566 Stars
836 Commits
112 Forks
17 Watching
5 Branches
30 Contributors
Updated on 28 Nov 2024
Bundle Size
74.66 kB
Minified
22.37 kB
Minified + Gzipped
Languages
JavaScript (57.47%)
TypeScript (42.53%)
Total Downloads
Cumulative downloads
Total Downloads
8,072,794,939
Last day
-7%
9,967,128
Compared to previous day
Last week
2.4%
57,894,047
Compared to previous week
Last month
12.5%
237,048,926
Compared to previous month
Last year
13.4%
2,438,367,071
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
fast-glob
This package provides methods for traversing the file system and returning pathnames that matched a defined set of a specified pattern according to the rules used by the Unix Bash shell with some simplifications, meanwhile results are returned in arbitrary order. Quick, simple, effective.
Table of Contents
Highlights
- Fast. Probably the fastest.
- Supports multiple and negative patterns.
- Synchronous, Promise and Stream API.
- Object mode. Can return more than just strings.
- Error-tolerant.
Pattern syntax
:warning: Always use forward-slashes in glob expressions (patterns and
ignore
option). Use backslashes for escaping characters.
There is more than one form of syntax: basic and advanced. Below is a brief overview of the supported features. Also pay attention to our FAQ.
:book: This package uses
micromatch
as a library for pattern matching.
Basic syntax
- An asterisk (
*
) — matches everything except slashes (path separators), hidden files (names starting with.
). - A double star or globstar (
**
) — matches zero or more directories. - Question mark (
?
) – matches any single character except slashes (path separators). - Sequence (
[seq]
) — matches any character in sequence.
:book: A few additional words about the basic matching behavior.
Some examples:
src/**/*.js
— matches all files in thesrc
directory (any level of nesting) that have the.js
extension.src/*.??
— matches all files in thesrc
directory (only first level of nesting) that have a two-character extension.file-[01].js
— matches files:file-0.js
,file-1.js
.
Advanced syntax
- Escapes characters (
\\
) — matching special characters ($^*+?()[]
) as literals. - POSIX character classes (
[[:digit:]]
). - Extended globs (
?(pattern-list)
). - Bash style brace expansions (
{}
). - Regexp character classes (
[1-5]
). - Regex groups (
(a|b)
).
:book: A few additional words about the advanced matching behavior.
Some examples:
src/**/*.{css,scss}
— matches all files in thesrc
directory (any level of nesting) that have the.css
or.scss
extension.file-[[:digit:]].js
— matches files:file-0.js
,file-1.js
, …,file-9.js
.file-{1..3}.js
— matches files:file-1.js
,file-2.js
,file-3.js
.file-(1|2)
— matches files:file-1.js
,file-2.js
.
Installation
1npm install fast-glob
API
Asynchronous
1fg.glob(patterns, [options]) 2fg.async(patterns, [options])
Returns a Promise
with an array of matching entries.
1const fg = require('fast-glob'); 2 3const entries = await fg.glob(['.editorconfig', '**/index.js'], { dot: true }); 4 5// ['.editorconfig', 'services/index.js']
Synchronous
1fg.globSync(patterns, [options])
Returns an array of matching entries.
1const fg = require('fast-glob'); 2 3const entries = fg.globSync(['.editorconfig', '**/index.js'], { dot: true }); 4 5// ['.editorconfig', 'services/index.js']
Stream
1fg.globStream(patterns, [options]) 2fg.stream(patterns, [options])
Returns a ReadableStream
when the data
event will be emitted with matching entry.
1const fg = require('fast-glob'); 2 3const stream = fg.globStream(['.editorconfig', '**/index.js'], { dot: true }); 4 5for await (const entry of stream) { 6 // .editorconfig 7 // services/index.js 8}
patterns
- Required:
true
- Type:
string | string[]
Any correct pattern(s).
:1234: Pattern syntax
:warning: This package does not respect the order of patterns. First, all the negative patterns are applied, and only then the positive patterns. If you want to get a certain order of records, use sorting or split calls.
[options]
- Required:
false
- Type:
Options
See Options section.
Helpers
generateTasks(patterns, [options])
Returns the internal representation of patterns (Task
is a combining patterns by base directory).
1fg.generateTasks('*'); 2 3[{ 4 base: '.', // Parent directory for all patterns inside this task 5 dynamic: true, // Dynamic or static patterns are in this task 6 patterns: ['*'], 7 positive: ['*'], 8 negative: [] 9}]
patterns
- Required:
true
- Type:
string | string[]
Any correct pattern(s).
[options]
- Required:
false
- Type:
Options
See Options section.
isDynamicPattern(pattern, [options])
Returns true
if the passed pattern is a dynamic pattern.
1fg.isDynamicPattern('*'); // true 2fg.isDynamicPattern('abc'); // false
pattern
- Required:
true
- Type:
string
Any correct pattern.
[options]
- Required:
false
- Type:
Options
See Options section.
escapePath(path)
Returns the path with escaped special characters depending on the platform.
- Posix:
*?|(){}[]
;!
at the beginning of line;@+!
before the opening parenthesis;\\
before non-special characters;
- Windows:
(){}[]
!
at the beginning of line;@+!
before the opening parenthesis;- Characters like
*?|
cannot be used in the path (windows_naming_conventions), so they will not be escaped;
1fg.escapePath('!abc'); 2// \\!abc 3fg.escapePath('[OpenSource] mrmlnc – fast-glob (Deluxe Edition) 2014') + '/*.flac' 4// \\[OpenSource\\] mrmlnc – fast-glob \\(Deluxe Edition\\) 2014/*.flac 5 6fg.posix.escapePath('C:\\Program Files (x86)\\**\\*'); 7// C:\\\\Program Files \\(x86\\)\\*\\*\\* 8fg.win32.escapePath('C:\\Program Files (x86)\\**\\*'); 9// Windows: C:\\Program Files \\(x86\\)\\**\\*
convertPathToPattern(path)
Converts a path to a pattern depending on the platform, including special character escaping.
- Posix. Works similarly to the
fg.posix.escapePath
method. - Windows. Works similarly to the
fg.win32.escapePath
method, additionally converting backslashes to forward slashes in cases where they are not escape characters (!()+@{}[]
).
1fg.convertPathToPattern('[OpenSource] mrmlnc – fast-glob (Deluxe Edition) 2014') + '/*.flac'; 2// \\[OpenSource\\] mrmlnc – fast-glob \\(Deluxe Edition\\) 2014/*.flac 3 4fg.convertPathToPattern('C:/Program Files (x86)/**/*'); 5// Posix: C:/Program Files \\(x86\\)/\\*\\*/\\* 6// Windows: C:/Program Files \\(x86\\)/**/* 7 8fg.convertPathToPattern('C:\\Program Files (x86)\\**\\*'); 9// Posix: C:\\\\Program Files \\(x86\\)\\*\\*\\* 10// Windows: C:/Program Files \\(x86\\)/**/* 11 12fg.posix.convertPathToPattern('\\\\?\\c:\\Program Files (x86)') + '/**/*'; 13// Posix: \\\\\\?\\\\c:\\\\Program Files \\(x86\\)/**/* (broken pattern) 14fg.win32.convertPathToPattern('\\\\?\\c:\\Program Files (x86)') + '/**/*'; 15// Windows: //?/c:/Program Files \\(x86\\)/**/*
Options
Common options
cwd
- Type:
string
- Default:
process.cwd()
The current working directory in which to search.
deep
- Type:
number
- Default:
Infinity
Specifies the maximum depth of a read directory relative to the start directory.
For example, you have the following tree:
1dir/ 2└── one/ // 1 3 └── two/ // 2 4 └── file.js // 3
1// With base directory
2fg.globSync('dir/**', { onlyFiles: false, deep: 1 }); // ['dir/one']
3fg.globSync('dir/**', { onlyFiles: false, deep: 2 }); // ['dir/one', 'dir/one/two']
4
5// With cwd option
6fg.globSync('**', { onlyFiles: false, cwd: 'dir', deep: 1 }); // ['one']
7fg.globSync('**', { onlyFiles: false, cwd: 'dir', deep: 2 }); // ['one', 'one/two']
:book: If you specify a pattern with some base directory, this directory will not participate in the calculation of the depth of the found directories. Think of it as a
cwd
option.
followSymbolicLinks
- Type:
boolean
- Default:
true
Indicates whether to traverse descendants of symbolic link directories when expanding **
patterns.
:book: Note that this option does not affect the base directory of the pattern. For example, if
./a
is a symlink to directory./b
and you specified['./a**', './b/**']
patterns, then directory./a
will still be read.
:book: If the
stats
option is specified, the information about the symbolic link (fs.lstat
) will be replaced with information about the entry (fs.stat
) behind it.
fs
- Type:
FileSystemAdapter
- Default:
fs.*
Custom implementation of methods for working with the file system. Supports objects with enumerable properties only.
1export interface FileSystemAdapter { 2 lstat?: typeof fs.lstat; 3 stat?: typeof fs.stat; 4 lstatSync?: typeof fs.lstatSync; 5 statSync?: typeof fs.statSync; 6 readdir?: typeof fs.readdir; 7 readdirSync?: typeof fs.readdirSync; 8}
ignore
- Type:
string[]
- Default:
[]
An array of glob patterns to exclude matches. This is an alternative way to use negative patterns.
1dir/ 2├── package-lock.json 3└── package.json
1fg.globSync(['*.json', '!package-lock.json']); // ['package.json']
2fg.globSync('*.json', { ignore: ['package-lock.json'] }); // ['package.json']
suppressErrors
- Type:
boolean
- Default:
false
By default this package suppress only ENOENT
errors. Set to true
to suppress any error.
:book: Can be useful when the directory has entries with a special level of access.
throwErrorOnBrokenSymbolicLink
- Type:
boolean
- Default:
false
Throw an error when symbolic link is broken if true
or safely return lstat
call if false
.
:book: This option has no effect on errors when reading the symbolic link directory.
Output control
absolute
- Type:
boolean
- Default:
false
Return the absolute path for entries.
1fg.globSync('*.js', { absolute: false }); // ['index.js']
2fg.globSync('*.js', { absolute: true }); // ['/home/user/index.js']
:book: This option is required if you want to use negative patterns with absolute path, for example,
!${__dirname}/*.js
.
markDirectories
- Type:
boolean
- Default:
false
Mark the directory path with the final slash.
1fg.globSync('*', { onlyFiles: false, markDirectories: false }); // ['index.js', 'controllers'] 2fg.globSync('*', { onlyFiles: false, markDirectories: true }); // ['index.js', 'controllers/']
objectMode
- Type:
boolean
- Default:
false
Returns objects (instead of strings) describing entries.
1fg.globSync('*', { objectMode: false }); // ['src/index.js'] 2fg.globSync('*', { objectMode: true }); // [{ name: 'index.js', path: 'src/index.js', dirent: <fs.Dirent> }]
The object has the following fields:
- name (
string
) — the last part of the path (basename) - path (
string
) — full path relative to the pattern base directory - dirent (
fs.Dirent
) — instance offs.Dirent
:book: An object is an internal representation of entry, so getting it does not affect performance.
onlyDirectories
- Type:
boolean
- Default:
false
Return only directories.
1fg.globSync('*', { onlyDirectories: false }); // ['index.js', 'src'] 2fg.globSync('*', { onlyDirectories: true }); // ['src']
:book: If
true
, theonlyFiles
option is automaticallyfalse
.
onlyFiles
- Type:
boolean
- Default:
true
Return everything (file, socket, …) except directories.
1fg.globSync('*', { onlyFiles: false }); // ['index.js', 'src'] 2fg.globSync('*', { onlyFiles: true }); // ['index.js']
stats
- Type:
boolean
- Default:
false
Enables an object mode with an additional field:
- stats (
fs.Stats
) — instance offs.Stats
1fg.globSync('*', { stats: false }); // ['src/index.js'] 2fg.globSync('*', { stats: true }); // [{ name: 'index.js', path: 'src/index.js', dirent: <fs.Dirent>, stats: <fs.Stats> }]
:book: Returns
fs.stat
instead offs.lstat
for symbolic links when thefollowSymbolicLinks
option is specified.
unique
- Type:
boolean
- Default:
true
Ensures that the returned entries are unique.
1fg.globSync(['*.json', 'package.json'], { unique: false }); // ['package.json', 'package.json'] 2fg.globSync(['*.json', 'package.json'], { unique: true }); // ['package.json']
If true
and similar entries are found, the result is the first found.
Matching control
braceExpansion
- Type:
boolean
- Default:
true
Enables Bash-like brace expansion.
:1234: Syntax description or more detailed description.
1dir/ 2├── abd 3├── acd 4└── a{b,c}d
1fg.globSync('a{b,c}d', { braceExpansion: false }); // ['a{b,c}d']
2fg.globSync('a{b,c}d', { braceExpansion: true }); // ['abd', 'acd']
caseSensitiveMatch
- Type:
boolean
- Default:
true
Enables a case-sensitive mode for matching files.
1dir/ 2├── file.txt 3└── File.txt
1fg.globSync('file.txt', { caseSensitiveMatch: false }); // ['file.txt', 'File.txt']
2fg.globSync('file.txt', { caseSensitiveMatch: true }); // ['file.txt']
dot
- Type:
boolean
- Default:
false
Allow patterns to match entries that begin with a period (.
).
:book: Note that an explicit dot in a portion of the pattern will always match dot files.
1dir/ 2├── .editorconfig 3└── package.json
1fg.globSync('*', { dot: false }); // ['package.json'] 2fg.globSync('*', { dot: true }); // ['.editorconfig', 'package.json']
extglob
- Type:
boolean
- Default:
true
Enables Bash-like extglob
functionality.
:1234: Syntax description.
1dir/ 2├── README.md 3└── package.json
1fg.globSync('*.+(json|md)', { extglob: false }); // []
2fg.globSync('*.+(json|md)', { extglob: true }); // ['README.md', 'package.json']
globstar
- Type:
boolean
- Default:
true
Enables recursively repeats a pattern containing **
. If false
, **
behaves exactly like *
.
1dir/ 2└── a 3 └── b
1fg.globSync('**', { onlyFiles: false, globstar: false }); // ['a'] 2fg.globSync('**', { onlyFiles: false, globstar: true }); // ['a', 'a/b']
baseNameMatch
- Type:
boolean
- Default:
false
If set to true
, then patterns without slashes will be matched against the basename of the path if it contains slashes.
1dir/ 2└── one/ 3 └── file.md
1fg.globSync('*.md', { baseNameMatch: false }); // []
2fg.globSync('*.md', { baseNameMatch: true }); // ['one/file.md']
FAQ
What is a static or dynamic pattern?
All patterns can be divided into two types:
- static. A pattern is considered static if it can be used to get an entry on the file system without using matching mechanisms. For example, the
file.js
pattern is a static pattern because we can just verify that it exists on the file system. - dynamic. A pattern is considered dynamic if it cannot be used directly to find occurrences without using a matching mechanisms. For example, the
*
pattern is a dynamic pattern because we cannot use this pattern directly.
A pattern is considered dynamic if it contains the following characters (…
— any characters or their absence) or options:
- The
caseSensitiveMatch
option is disabled \\
(the escape character)*
,?
,!
(at the beginning of line)[…]
(…|…)
@(…)
,!(…)
,*(…)
,?(…)
,+(…)
(respects theextglob
option){…,…}
,{…..…}
(respects thebraceExpansion
option)
How to write patterns on Windows?
Always use forward-slashes in glob expressions (patterns and ignore
option). Use backslashes for escaping characters. With the cwd
option use a convenient format.
Bad
1[ 2 'directory\\*', 3 path.join(process.cwd(), '**') 4]
Good
1[ 2 'directory/*', 3 fg.convertPathToPattern(process.cwd()) + '/**' 4]
:book: Use the
.convertPathToPattern
package to convert Windows-style path to a Unix-style path.
Read more about matching with backslashes.
Why are parentheses match wrong?
1dir/ 2└── (special-*file).txt
1fg.globSync(['(special-*file).txt']) // []
Refers to Bash. You need to escape special characters:
1fg.globSync(['\\(special-*file\\).txt']) // ['(special-*file).txt']
Read more about matching special characters as literals. Or use the .escapePath
.
How to exclude directory from reading?
You can use a negative pattern like this: !**/node_modules
or !**/node_modules/**
. Also you can use ignore
option. Just look at the example below.
1first/ 2├── file.md 3└── second/ 4 └── file.txt
If you don't want to read the second
directory, you must write the following pattern: !**/second
or !**/second/**
.
1fg.globSync(['**/*.md', '!**/second']); // ['first/file.md'] 2fg.globSync(['**/*.md'], { ignore: ['**/second/**'] }); // ['first/file.md']
:warning: When you write
!**/second/**/*
it means that the directory will be read, but all the entries will not be included in the results.
You have to understand that if you write the pattern to exclude directories, then the directory will not be read under any circumstances.
How to use UNC path?
You cannot use Uniform Naming Convention (UNC) paths as patterns (due to syntax) directly, but you can use them as cwd
directory or use the fg.convertPathToPattern
method.
1// cwd 2fg.globSync('*', { cwd: '\\\\?\\C:\\Python27' /* or //?/C:/Python27 */ }); 3fg.globSync('Python27/*', { cwd: '\\\\?\\C:\\' /* or //?/C:/ */ }); 4 5// .convertPathToPattern 6fg.globSync(fg.convertPathToPattern('\\\\?\\c:\\Python27') + '/*');
Compatible with node-glob
?
node-glob | fast-glob |
---|---|
cwd | cwd |
root | – |
dot | dot |
nomount | – |
mark | markDirectories |
nosort | – |
nounique | unique |
nobrace | braceExpansion |
noglobstar | globstar |
noext | extglob |
nocase | caseSensitiveMatch |
matchBase | baseNameMatch |
nodir | onlyFiles |
ignore | ignore |
follow | followSymbolicLinks |
realpath | – |
absolute | absolute |
Benchmarks
You can see results here for every commit into the main
branch.
- Product benchmark – comparison with the main competitors.
- Regress benchmark – regression between the current version and the version from the npm registry.
Changelog
See the Releases section of our GitHub project for changelog for each release version.
License
This software is released under the terms of the MIT license.
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
0 existing vulnerabilities detected
Reason
license file detected
Details
- Info: project has a license file: LICENSE:0
- Info: FSF or OSI recognized license: MIT License: LICENSE:0
Reason
SAST tool detected but not run on all commits
Details
- Info: SAST configuration detected: CodeQL
- Warn: 25 commits out of 29 are checked with a SAST tool
Reason
Found 3/12 approved changesets -- score normalized to 2
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
detected GitHub workflow tokens with excessive permissions
Details
- Info: jobLevel 'actions' permission set to 'read': .github/workflows/codeql.yml:20
- Info: jobLevel 'contents' permission set to 'read': .github/workflows/codeql.yml:21
- Warn: no topLevel permission defined: .github/workflows/benchmark.yml:1
- Warn: no topLevel permission defined: .github/workflows/codeql.yml:1
- Warn: no topLevel permission defined: .github/workflows/main.yml:1
- Info: no jobLevel write permissions found
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/benchmark.yml:18: update your workflow using https://app.stepsecurity.io/secureworkflow/mrmlnc/fast-glob/benchmark.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/benchmark.yml:20: update your workflow using https://app.stepsecurity.io/secureworkflow/mrmlnc/fast-glob/benchmark.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/benchmark.yml:51: update your workflow using https://app.stepsecurity.io/secureworkflow/mrmlnc/fast-glob/benchmark.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/benchmark.yml:53: update your workflow using https://app.stepsecurity.io/secureworkflow/mrmlnc/fast-glob/benchmark.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/codeql.yml:26: update your workflow using https://app.stepsecurity.io/secureworkflow/mrmlnc/fast-glob/codeql.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/codeql.yml:31: update your workflow using https://app.stepsecurity.io/secureworkflow/mrmlnc/fast-glob/codeql.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/codeql.yml:37: update your workflow using https://app.stepsecurity.io/secureworkflow/mrmlnc/fast-glob/codeql.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/codeql.yml:40: update your workflow using https://app.stepsecurity.io/secureworkflow/mrmlnc/fast-glob/codeql.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/main.yml:29: update your workflow using https://app.stepsecurity.io/secureworkflow/mrmlnc/fast-glob/main.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/main.yml:31: update your workflow using https://app.stepsecurity.io/secureworkflow/mrmlnc/fast-glob/main.yml/master?enable=pin
- Warn: npmCommand not pinned by hash: .github/workflows/benchmark.yml:25
- Warn: npmCommand not pinned by hash: .github/workflows/benchmark.yml:58
- Warn: npmCommand not pinned by hash: .github/workflows/main.yml:36
- Info: 0 out of 10 GitHub-owned GitHubAction dependencies pinned
- Info: 0 out of 3 npmCommand dependencies pinned
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
- Warn: no security policy file detected
- Warn: no security file to analyze
- Warn: no security file to analyze
- Warn: no security file to analyze
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
Project has not signed or included provenance with any releases.
Details
- Warn: release artifact 3.3.2 not signed: https://api.github.com/repos/mrmlnc/fast-glob/releases/128127846
- Warn: release artifact 3.3.1 not signed: https://api.github.com/repos/mrmlnc/fast-glob/releases/113183483
- Warn: release artifact 3.3.0 not signed: https://api.github.com/repos/mrmlnc/fast-glob/releases/108148714
- Warn: release artifact 3.2.12 not signed: https://api.github.com/repos/mrmlnc/fast-glob/releases/76679412
- Warn: release artifact 3.2.11 not signed: https://api.github.com/repos/mrmlnc/fast-glob/releases/57148130
- Warn: release artifact 3.3.2 does not have provenance: https://api.github.com/repos/mrmlnc/fast-glob/releases/128127846
- Warn: release artifact 3.3.1 does not have provenance: https://api.github.com/repos/mrmlnc/fast-glob/releases/113183483
- Warn: release artifact 3.3.0 does not have provenance: https://api.github.com/repos/mrmlnc/fast-glob/releases/108148714
- Warn: release artifact 3.2.12 does not have provenance: https://api.github.com/repos/mrmlnc/fast-glob/releases/76679412
- Warn: release artifact 3.2.11 does not have provenance: https://api.github.com/repos/mrmlnc/fast-glob/releases/57148130
Score
4.2
/10
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More