• Home
Name Date Size #Lines LOC

..--

dist/12-May-2024-4,3083,087

LICENSED12-May-2024775 1612

README.mdD12-May-202445.3 KiB1,213958

package.jsonD12-May-20242.6 KiB9998

README.md

1# Glob
2
3Match files using the patterns the shell uses.
4
5The most correct and second fastest glob implementation in
6JavaScript. (See **Comparison to Other JavaScript Glob
7Implementations** at the bottom of this readme.)
8
9![a fun cartoon logo made of glob characters](https://github.com/isaacs/node-glob/raw/main/logo/glob.png)
10
11## Usage
12
13Install with npm
14
15```
16npm i glob
17```
18
19**Note** the npm package name is _not_ `node-glob` that's a
20different thing that was abandoned years ago. Just `glob`.
21
22```js
23// load using import
24import { glob, globSync, globStream, globStreamSync, Glob } from 'glob'
25// or using commonjs, that's fine, too
26const {
27  glob,
28  globSync,
29  globStream,
30  globStreamSync,
31  Glob,
32} = require('glob')
33
34// the main glob() and globSync() resolve/return array of filenames
35
36// all js files, but don't look in node_modules
37const jsfiles = await glob('**/*.js', { ignore: 'node_modules/**' })
38
39// pass in a signal to cancel the glob walk
40const stopAfter100ms = await glob('**/*.css', {
41  signal: AbortSignal.timeout(100),
42})
43
44// multiple patterns supported as well
45const images = await glob(['css/*.{png,jpeg}', 'public/*.{png,jpeg}'])
46
47// but of course you can do that with the glob pattern also
48// the sync function is the same, just returns a string[] instead
49// of Promise<string[]>
50const imagesAlt = globSync('{css,public}/*.{png,jpeg}')
51
52// you can also stream them, this is a Minipass stream
53const filesStream = globStream(['**/*.dat', 'logs/**/*.log'])
54
55// construct a Glob object if you wanna do it that way, which
56// allows for much faster walks if you have to look in the same
57// folder multiple times.
58const g = new Glob('**/foo')
59// glob objects are async iterators, can also do globIterate() or
60// g.iterate(), same deal
61for await (const file of g) {
62  console.log('found a foo file:', file)
63}
64// pass a glob as the glob options to reuse its settings and caches
65const g2 = new Glob('**/bar', g)
66// sync iteration works as well
67for (const file of g2) {
68  console.log('found a bar file:', file)
69}
70
71// you can also pass withFileTypes: true to get Path objects
72// these are like a Dirent, but with some more added powers
73// check out http://npm.im/path-scurry for more info on their API
74const g3 = new Glob('**/baz/**', { withFileTypes: true })
75g3.stream().on('data', path => {
76  console.log(
77    'got a path object',
78    path.fullpath(),
79    path.isDirectory(),
80    path.readdirSync().map(e => e.name)
81  )
82})
83
84// if you use stat:true and withFileTypes, you can sort results
85// by things like modified time, filter by permission mode, etc.
86// All Stats fields will be available in that case. Slightly
87// slower, though.
88// For example:
89const results = await glob('**', { stat: true, withFileTypes: true })
90
91const timeSortedFiles = results
92  .sort((a, b) => a.mtimeMS - b.mtimeMS)
93  .map(path => path.fullpath())
94
95const groupReadableFiles = results
96  .filter(path => path.mode & 0o040)
97  .map(path => path.fullpath())
98
99// custom ignores can be done like this, for example by saying
100// you'll ignore all markdown files, and all folders named 'docs'
101const customIgnoreResults = await glob('**', {
102  ignore: {
103    ignored: p => /\.md$/.test(p.name),
104    childrenIgnored: p => p.isNamed('docs'),
105  },
106})
107
108// another fun use case, only return files with the same name as
109// their parent folder, plus either `.ts` or `.js`
110const folderNamedModules = await glob('**/*.{ts,js}', {
111  ignore: {
112    ignored: p => {
113      const pp = p.parent
114      return !(p.isNamed(pp.name + '.ts') || p.isNamed(pp.name + '.js'))
115    },
116  },
117})
118
119// find all files edited in the last hour, to do this, we ignore
120// all of them that are more than an hour old
121const newFiles = await glob('**', {
122  // need stat so we have mtime
123  stat: true,
124  // only want the files, not the dirs
125  nodir: true,
126  ignore: {
127    ignored: p => {
128      return new Date() - p.mtime > 60 * 60 * 1000
129    },
130    // could add similar childrenIgnored here as well, but
131    // directory mtime is inconsistent across platforms, so
132    // probably better not to, unless you know the system
133    // tracks this reliably.
134  },
135})
136```
137
138**Note** Glob patterns should always use `/` as a path separator,
139even on Windows systems, as `\` is used to escape glob
140characters. If you wish to use `\` as a path separator _instead
141of_ using it as an escape character on Windows platforms, you may
142set `windowsPathsNoEscape:true` in the options. In this mode,
143special glob characters cannot be escaped, making it impossible
144to match a literal `*` `?` and so on in filenames.
145
146## Command Line Interface
147
148```
149$ glob -h
150
151Usage:
152  glob [options] [<pattern> [<pattern> ...]]
153
154Expand the positional glob expression arguments into any matching file system
155paths found.
156
157  -c<command> --cmd=<command>
158                         Run the command provided, passing the glob expression
159                         matches as arguments.
160
161  -A --all               By default, the glob cli command will not expand any
162                         arguments that are an exact match to a file on disk.
163
164                         This prevents double-expanding, in case the shell
165                         expands an argument whose filename is a glob
166                         expression.
167
168                         For example, if 'app/*.ts' would match 'app/[id].ts',
169                         then on Windows powershell or cmd.exe, 'glob app/*.ts'
170                         will expand to 'app/[id].ts', as expected. However, in
171                         posix shells such as bash or zsh, the shell will first
172                         expand 'app/*.ts' to a list of filenames. Then glob
173                         will look for a file matching 'app/[id].ts' (ie,
174                         'app/i.ts' or 'app/d.ts'), which is unexpected.
175
176                         Setting '--all' prevents this behavior, causing glob to
177                         treat ALL patterns as glob expressions to be expanded,
178                         even if they are an exact match to a file on disk.
179
180                         When setting this option, be sure to enquote arguments
181                         so that the shell will not expand them prior to passing
182                         them to the glob command process.
183
184  -a --absolute          Expand to absolute paths
185  -d --dot-relative      Prepend './' on relative matches
186  -m --mark              Append a / on any directories matched
187  -x --posix             Always resolve to posix style paths, using '/' as the
188                         directory separator, even on Windows. Drive letter
189                         absolute matches on Windows will be expanded to their
190                         full resolved UNC maths, eg instead of 'C:\foo\bar', it
191                         will expand to '//?/C:/foo/bar'.
192
193  -f --follow            Follow symlinked directories when expanding '**'
194  -R --realpath          Call 'fs.realpath' on all of the results. In the case
195                         of an entry that cannot be resolved, the entry is
196                         omitted. This incurs a slight performance penalty, of
197                         course, because of the added system calls.
198
199  -s --stat              Call 'fs.lstat' on all entries, whether required or not
200                         to determine if it's a valid match.
201
202  -b --match-base        Perform a basename-only match if the pattern does not
203                         contain any slash characters. That is, '*.js' would be
204                         treated as equivalent to '**/*.js', matching js files
205                         in all directories.
206
207  --dot                  Allow patterns to match files/directories that start
208                         with '.', even if the pattern does not start with '.'
209
210  --nobrace              Do not expand {...} patterns
211  --nocase               Perform a case-insensitive match. This defaults to
212                         'true' on macOS and Windows platforms, and false on all
213                         others.
214
215                         Note: 'nocase' should only be explicitly set when it is
216                         known that the filesystem's case sensitivity differs
217                         from the platform default. If set 'true' on
218                         case-insensitive file systems, then the walk may return
219                         more or less results than expected.
220
221  --nodir                Do not match directories, only files.
222
223                         Note: to *only* match directories, append a '/' at the
224                         end of the pattern.
225
226  --noext                Do not expand extglob patterns, such as '+(a|b)'
227  --noglobstar           Do not expand '**' against multiple path portions. Ie,
228                         treat it as a normal '*' instead.
229
230  --windows-path-no-escape
231                         Use '\' as a path separator *only*, and *never* as an
232                         escape character. If set, all '\' characters are
233                         replaced with '/' in the pattern.
234
235  -D<n> --max-depth=<n>  Maximum depth to traverse from the current working
236                         directory
237
238  -C<cwd> --cwd=<cwd>    Current working directory to execute/match in
239  -r<root> --root=<root> A string path resolved against the 'cwd', which is used
240                         as the starting point for absolute patterns that start
241                         with '/' (but not drive letters or UNC paths on
242                         Windows).
243
244                         Note that this *doesn't* necessarily limit the walk to
245                         the 'root' directory, and doesn't affect the cwd
246                         starting point for non-absolute patterns. A pattern
247                         containing '..' will still be able to traverse out of
248                         the root directory, if it is not an actual root
249                         directory on the filesystem, and any non-absolute
250                         patterns will still be matched in the 'cwd'.
251
252                         To start absolute and non-absolute patterns in the same
253                         path, you can use '--root=' to set it to the empty
254                         string. However, be aware that on Windows systems, a
255                         pattern like 'x:/*' or '//host/share/*' will *always*
256                         start in the 'x:/' or '//host/share/' directory,
257                         regardless of the --root setting.
258
259  --platform=<platform>  Defaults to the value of 'process.platform' if
260                         available, or 'linux' if not. Setting --platform=win32
261                         on non-Windows systems may cause strange behavior!
262
263  -i<ignore> --ignore=<ignore>
264                         Glob patterns to ignore Can be set multiple times
265  -v --debug             Output a huge amount of noisy debug information about
266                         patterns as they are parsed and used to match files.
267
268  -h --help              Show this usage information
269```
270
271## `glob(pattern: string | string[], options?: GlobOptions) => Promise<string[] | Path[]>`
272
273Perform an asynchronous glob search for the pattern(s) specified.
274Returns
275[Path](https://isaacs.github.io/path-scurry/classes/PathBase)
276objects if the `withFileTypes` option is set to `true`. See below
277for full options field desciptions.
278
279## `globSync(pattern: string | string[], options?: GlobOptions) => string[] | Path[]`
280
281Synchronous form of `glob()`.
282
283Alias: `glob.sync()`
284
285## `globIterate(pattern: string | string[], options?: GlobOptions) => AsyncGenerator<string>`
286
287Return an async iterator for walking glob pattern matches.
288
289Alias: `glob.iterate()`
290
291## `globIterateSync(pattern: string | string[], options?: GlobOptions) => Generator<string>`
292
293Return a sync iterator for walking glob pattern matches.
294
295Alias: `glob.iterate.sync()`, `glob.sync.iterate()`
296
297## `globStream(pattern: string | string[], options?: GlobOptions) => Minipass<string | Path>`
298
299Return a stream that emits all the strings or `Path` objects and
300then emits `end` when completed.
301
302Alias: `glob.stream()`
303
304## `globStreamSync(pattern: string | string[], options?: GlobOptions) => Minipass<string | Path>`
305
306Syncronous form of `globStream()`. Will read all the matches as
307fast as you consume them, even all in a single tick if you
308consume them immediately, but will still respond to backpressure
309if they're not consumed immediately.
310
311Alias: `glob.stream.sync()`, `glob.sync.stream()`
312
313## `hasMagic(pattern: string | string[], options?: GlobOptions) => boolean`
314
315Returns `true` if the provided pattern contains any "magic" glob
316characters, given the options provided.
317
318Brace expansion is not considered "magic" unless the
319`magicalBraces` option is set, as brace expansion just turns one
320string into an array of strings. So a pattern like `'x{a,b}y'`
321would return `false`, because `'xay'` and `'xby'` both do not
322contain any magic glob characters, and it's treated the same as
323if you had called it on `['xay', 'xby']`. When
324`magicalBraces:true` is in the options, brace expansion _is_
325treated as a pattern having magic.
326
327## `escape(pattern: string, options?: GlobOptions) => string`
328
329Escape all magic characters in a glob pattern, so that it will
330only ever match literal strings
331
332If the `windowsPathsNoEscape` option is used, then characters are
333escaped by wrapping in `[]`, because a magic character wrapped in
334a character class can only be satisfied by that exact character.
335
336Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot
337be escaped or unescaped.
338
339## `unescape(pattern: string, options?: GlobOptions) => string`
340
341Un-escape a glob string that may contain some escaped characters.
342
343If the `windowsPathsNoEscape` option is used, then square-brace
344escapes are removed, but not backslash escapes. For example, it
345will turn the string `'[*]'` into `*`, but it will not turn
346`'\\*'` into `'*'`, because `\` is a path separator in
347`windowsPathsNoEscape` mode.
348
349When `windowsPathsNoEscape` is not set, then both brace escapes
350and backslash escapes are removed.
351
352Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot
353be escaped or unescaped.
354
355## Class `Glob`
356
357An object that can perform glob pattern traversals.
358
359### `const g = new Glob(pattern: string | string[], options: GlobOptions)`
360
361See full options descriptions below.
362
363Note that a previous `Glob` object can be passed as the
364`GlobOptions` to another `Glob` instantiation to re-use settings
365and caches with a new pattern.
366
367Traversal functions can be called multiple times to run the walk
368again.
369
370### `g.stream()`
371
372Stream results asynchronously,
373
374### `g.streamSync()`
375
376Stream results synchronously.
377
378### `g.iterate()`
379
380Default async iteration function. Returns an AsyncGenerator that
381iterates over the results.
382
383### `g.iterateSync()`
384
385Default sync iteration function. Returns a Generator that
386iterates over the results.
387
388### `g.walk()`
389
390Returns a Promise that resolves to the results array.
391
392### `g.walkSync()`
393
394Returns a results array.
395
396### Properties
397
398All options are stored as properties on the `Glob` object.
399
400- `opts` The options provided to the constructor.
401- `patterns` An array of parsed immutable `Pattern` objects.
402
403## Options
404
405Exported as `GlobOptions` TypeScript interface. A `GlobOptions`
406object may be provided to any of the exported methods, and must
407be provided to the `Glob` constructor.
408
409All options are optional, boolean, and false by default, unless
410otherwise noted.
411
412All resolved options are added to the Glob object as properties.
413
414If you are running many `glob` operations, you can pass a Glob
415object as the `options` argument to a subsequent operation to
416share the previously loaded cache.
417
418- `cwd` String path or `file://` string or URL object. The
419  current working directory in which to search. Defaults to
420  `process.cwd()`. See also: "Windows, CWDs, Drive Letters, and
421  UNC Paths", below.
422
423  This option may be eiher a string path or a `file://` URL
424  object or string.
425
426- `root` A string path resolved against the `cwd` option, which
427  is used as the starting point for absolute patterns that start
428  with `/`, (but not drive letters or UNC paths on Windows).
429
430  Note that this _doesn't_ necessarily limit the walk to the
431  `root` directory, and doesn't affect the cwd starting point for
432  non-absolute patterns. A pattern containing `..` will still be
433  able to traverse out of the root directory, if it is not an
434  actual root directory on the filesystem, and any non-absolute
435  patterns will be matched in the `cwd`. For example, the
436  pattern `/../*` with `{root:'/some/path'}` will return all
437  files in `/some`, not all files in `/some/path`. The pattern
438  `*` with `{root:'/some/path'}` will return all the entries in
439  the cwd, not the entries in `/some/path`.
440
441  To start absolute and non-absolute patterns in the same
442  path, you can use `{root:''}`. However, be aware that on
443  Windows systems, a pattern like `x:/*` or `//host/share/*` will
444  _always_ start in the `x:/` or `//host/share` directory,
445  regardless of the `root` setting.
446
447- `windowsPathsNoEscape` Use `\\` as a path separator _only_, and
448  _never_ as an escape character. If set, all `\\` characters are
449  replaced with `/` in the pattern.
450
451  Note that this makes it **impossible** to match against paths
452  containing literal glob pattern characters, but allows matching
453  with patterns constructed using `path.join()` and
454  `path.resolve()` on Windows platforms, mimicking the (buggy!)
455  behavior of Glob v7 and before on Windows. Please use with
456  caution, and be mindful of [the caveat below about Windows
457  paths](#windows). (For legacy reasons, this is also set if
458  `allowWindowsEscape` is set to the exact value `false`.)
459
460- `dot` Include `.dot` files in normal matches and `globstar`
461  matches. Note that an explicit dot in a portion of the pattern
462  will always match dot files.
463
464- `magicalBraces` Treat brace expansion like `{a,b}` as a "magic"
465  pattern. Has no effect if {@link nobrace} is set.
466
467  Only has effect on the {@link hasMagic} function, no effect on
468  glob pattern matching itself.
469
470- `dotRelative` Prepend all relative path strings with `./` (or
471  `.\` on Windows).
472
473  Without this option, returned relative paths are "bare", so
474  instead of returning `'./foo/bar'`, they are returned as
475  `'foo/bar'`.
476
477  Relative patterns starting with `'../'` are not prepended with
478  `./`, even if this option is set.
479
480- `mark` Add a `/` character to directory matches. Note that this
481  requires additional stat calls.
482
483- `nobrace` Do not expand `{a,b}` and `{1..3}` brace sets.
484
485- `noglobstar` Do not match `**` against multiple filenames. (Ie,
486  treat it as a normal `*` instead.)
487
488- `noext` Do not match "extglob" patterns such as `+(a|b)`.
489
490- `nocase` Perform a case-insensitive match. This defaults to
491  `true` on macOS and Windows systems, and `false` on all others.
492
493  **Note** `nocase` should only be explicitly set when it is
494  known that the filesystem's case sensitivity differs from the
495  platform default. If set `true` on case-sensitive file
496  systems, or `false` on case-insensitive file systems, then the
497  walk may return more or less results than expected.
498
499- `maxDepth` Specify a number to limit the depth of the directory
500  traversal to this many levels below the `cwd`.
501
502- `matchBase` Perform a basename-only match if the pattern does
503  not contain any slash characters. That is, `*.js` would be
504  treated as equivalent to `**/*.js`, matching all js files in
505  all directories.
506
507- `nodir` Do not match directories, only files. (Note: to match
508  _only_ directories, put a `/` at the end of the pattern.)
509
510- `stat` Call `lstat()` on all entries, whether required or not
511  to determine whether it's a valid match. When used with
512  `withFileTypes`, this means that matches will include data such
513  as modified time, permissions, and so on. Note that this will
514  incur a performance cost due to the added system calls.
515
516- `ignore` string or string[], or an object with `ignore` and
517  `ignoreChildren` methods.
518
519  If a string or string[] is provided, then this is treated as a
520  glob pattern or array of glob patterns to exclude from matches.
521  To ignore all children within a directory, as well as the entry
522  itself, append `'/**'` to the ignore pattern.
523
524  **Note** `ignore` patterns are _always_ in `dot:true` mode,
525  regardless of any other settings.
526
527  If an object is provided that has `ignored(path)` and/or
528  `childrenIgnored(path)` methods, then these methods will be
529  called to determine whether any Path is a match or if its
530  children should be traversed, respectively.
531
532- `follow` Follow symlinked directories when expanding `**`
533  patterns. This can result in a lot of duplicate references in
534  the presence of cyclic links, and make performance quite bad.
535
536  By default, a `**` in a pattern will follow 1 symbolic link if
537  it is not the first item in the pattern, or none if it is the
538  first item in the pattern, following the same behavior as Bash.
539
540- `realpath` Set to true to call `fs.realpath` on all of the
541  results. In the case of an entry that cannot be resolved, the
542  entry is omitted. This incurs a slight performance penalty, of
543  course, because of the added system calls.
544
545- `absolute` Set to true to always receive absolute paths for
546  matched files. Set to `false` to always receive relative paths
547  for matched files.
548
549  By default, when this option is not set, absolute paths are
550  returned for patterns that are absolute, and otherwise paths
551  are returned that are relative to the `cwd` setting.
552
553  This does _not_ make an extra system call to get the realpath,
554  it only does string path resolution.
555
556  `absolute` may not be used along with `withFileTypes`.
557
558- `posix` Set to true to use `/` as the path separator in
559  returned results. On posix systems, this has no effect. On
560  Windows systems, this will return `/` delimited path results,
561  and absolute paths will be returned in their full resolved UNC
562  path form, eg insted of `'C:\\foo\\bar'`, it will return
563  `//?/C:/foo/bar`.
564
565- `platform` Defaults to value of `process.platform` if
566  available, or `'linux'` if not. Setting `platform:'win32'` on
567  non-Windows systems may cause strange behavior.
568
569- `withFileTypes` Return [PathScurry](http://npm.im/path-scurry)
570  `Path` objects instead of strings. These are similar to a
571  NodeJS `Dirent` object, but with additional methods and
572  properties.
573
574  `withFileTypes` may not be used along with `absolute`.
575
576- `signal` An AbortSignal which will cancel the Glob walk when
577  triggered.
578
579- `fs` An override object to pass in custom filesystem methods.
580  See [PathScurry docs](http://npm.im/path-scurry) for what can
581  be overridden.
582
583- `scurry` A [PathScurry](http://npm.im/path-scurry) object used
584  to traverse the file system. If the `nocase` option is set
585  explicitly, then any provided `scurry` object must match this
586  setting.
587
588## Glob Primer
589
590Much more information about glob pattern expansion can be found
591by running `man bash` and searching for `Pattern Matching`.
592
593"Globs" are the patterns you type when you do stuff like `ls
594*.js` on the command line, or put `build/*` in a `.gitignore`
595file.
596
597Before parsing the path part patterns, braced sections are
598expanded into a set. Braced sections start with `{` and end with
599`}`, with 2 or more comma-delimited sections within. Braced
600sections may contain slash characters, so `a{/b/c,bcd}` would
601expand into `a/b/c` and `abcd`.
602
603The following characters have special magic meaning when used in
604a path portion. With the exception of `**`, none of these match
605path separators (ie, `/` on all platforms, and `\` on Windows).
606
607- `*` Matches 0 or more characters in a single path portion.
608  When alone in a path portion, it must match at least 1
609  character. If `dot:true` is not specified, then `*` will not
610  match against a `.` character at the start of a path portion.
611- `?` Matches 1 character. If `dot:true` is not specified, then
612  `?` will not match against a `.` character at the start of a
613  path portion.
614- `[...]` Matches a range of characters, similar to a RegExp
615  range. If the first character of the range is `!` or `^` then
616  it matches any character not in the range. If the first
617  character is `]`, then it will be considered the same as `\]`,
618  rather than the end of the character class.
619- `!(pattern|pattern|pattern)` Matches anything that does not
620  match any of the patterns provided. May _not_ contain `/`
621  characters. Similar to `*`, if alone in a path portion, then
622  the path portion must have at least one character.
623- `?(pattern|pattern|pattern)` Matches zero or one occurrence of
624  the patterns provided. May _not_ contain `/` characters.
625- `+(pattern|pattern|pattern)` Matches one or more occurrences of
626  the patterns provided. May _not_ contain `/` characters.
627- `*(a|b|c)` Matches zero or more occurrences of the patterns
628  provided. May _not_ contain `/` characters.
629- `@(pattern|pat*|pat?erN)` Matches exactly one of the patterns
630  provided. May _not_ contain `/` characters.
631- `**` If a "globstar" is alone in a path portion, then it
632  matches zero or more directories and subdirectories searching
633  for matches. It does not crawl symlinked directories, unless
634  `{follow:true}` is passed in the options object. A pattern
635  like `a/b/**` will only match `a/b` if it is a directory.
636  Follows 1 symbolic link if not the first item in the pattern,
637  or 0 if it is the first item, unless `follow:true` is set, in
638  which case it follows all symbolic links.
639
640`[:class:]` patterns are supported by this implementation, but
641`[=c=]` and `[.symbol.]` style class patterns are not.
642
643### Dots
644
645If a file or directory path portion has a `.` as the first
646character, then it will not match any glob pattern unless that
647pattern's corresponding path part also has a `.` as its first
648character.
649
650For example, the pattern `a/.*/c` would match the file at
651`a/.b/c`. However the pattern `a/*/c` would not, because `*` does
652not start with a dot character.
653
654You can make glob treat dots as normal characters by setting
655`dot:true` in the options.
656
657### Basename Matching
658
659If you set `matchBase:true` in the options, and the pattern has
660no slashes in it, then it will seek for any file anywhere in the
661tree with a matching basename. For example, `*.js` would match
662`test/simple/basic.js`.
663
664### Empty Sets
665
666If no matching files are found, then an empty array is returned.
667This differs from the shell, where the pattern itself is
668returned. For example:
669
670```sh
671$ echo a*s*d*f
672a*s*d*f
673```
674
675## Comparisons to other fnmatch/glob implementations
676
677While strict compliance with the existing standards is a
678worthwhile goal, some discrepancies exist between node-glob and
679other implementations, and are intentional.
680
681The double-star character `**` is supported by default, unless
682the `noglobstar` flag is set. This is supported in the manner of
683bsdglob and bash 5, where `**` only has special significance if
684it is the only thing in a path part. That is, `a/**/b` will match
685`a/x/y/b`, but `a/**b` will not.
686
687Note that symlinked directories are not traversed as part of a
688`**`, though their contents may match against subsequent portions
689of the pattern. This prevents infinite loops and duplicates and
690the like. You can force glob to traverse symlinks with `**` by
691setting `{follow:true}` in the options.
692
693There is no equivalent of the `nonull` option. A pattern that
694does not find any matches simply resolves to nothing. (An empty
695array, immediately ended stream, etc.)
696
697If brace expansion is not disabled, then it is performed before
698any other interpretation of the glob pattern. Thus, a pattern
699like `+(a|{b),c)}`, which would not be valid in bash or zsh, is
700expanded **first** into the set of `+(a|b)` and `+(a|c)`, and
701those patterns are checked for validity. Since those two are
702valid, matching proceeds.
703
704The character class patterns `[:class:]` (posix standard named
705classes) style class patterns are supported and unicode-aware,
706but `[=c=]` (locale-specific character collation weight), and
707`[.symbol.]` (collating symbol), are not.
708
709### Repeated Slashes
710
711Unlike Bash and zsh, repeated `/` are always coalesced into a
712single path separator.
713
714### Comments and Negation
715
716Previously, this module let you mark a pattern as a "comment" if
717it started with a `#` character, or a "negated" pattern if it
718started with a `!` character.
719
720These options were deprecated in version 5, and removed in
721version 6.
722
723To specify things that should not match, use the `ignore` option.
724
725## Windows
726
727**Please only use forward-slashes in glob expressions.**
728
729Though windows uses either `/` or `\` as its path separator, only
730`/` characters are used by this glob implementation. You must use
731forward-slashes **only** in glob expressions. Back-slashes will
732always be interpreted as escape characters, not path separators.
733
734Results from absolute patterns such as `/foo/*` are mounted onto
735the root setting using `path.join`. On windows, this will by
736default result in `/foo/*` matching `C:\foo\bar.txt`.
737
738To automatically coerce all `\` characters to `/` in pattern
739strings, **thus making it impossible to escape literal glob
740characters**, you may set the `windowsPathsNoEscape` option to
741`true`.
742
743### Windows, CWDs, Drive Letters, and UNC Paths
744
745On posix systems, when a pattern starts with `/`, any `cwd`
746option is ignored, and the traversal starts at `/`, plus any
747non-magic path portions specified in the pattern.
748
749On Windows systems, the behavior is similar, but the concept of
750an "absolute path" is somewhat more involved.
751
752#### UNC Paths
753
754A UNC path may be used as the start of a pattern on Windows
755platforms. For example, a pattern like: `//?/x:/*` will return
756all file entries in the root of the `x:` drive. A pattern like
757`//ComputerName/Share/*` will return all files in the associated
758share.
759
760UNC path roots are always compared case insensitively.
761
762#### Drive Letters
763
764A pattern starting with a drive letter, like `c:/*`, will search
765in that drive, regardless of any `cwd` option provided.
766
767If the pattern starts with `/`, and is not a UNC path, and there
768is an explicit `cwd` option set with a drive letter, then the
769drive letter in the `cwd` is used as the root of the directory
770traversal.
771
772For example, `glob('/tmp', { cwd: 'c:/any/thing' })` will return
773`['c:/tmp']` as the result.
774
775If an explicit `cwd` option is not provided, and the pattern
776starts with `/`, then the traversal will run on the root of the
777drive provided as the `cwd` option. (That is, it is the result of
778`path.resolve('/')`.)
779
780## Race Conditions
781
782Glob searching, by its very nature, is susceptible to race
783conditions, since it relies on directory walking.
784
785As a result, it is possible that a file that exists when glob
786looks for it may have been deleted or modified by the time it
787returns the result.
788
789By design, this implementation caches all readdir calls that it
790makes, in order to cut down on system overhead. However, this
791also makes it even more susceptible to races, especially if the
792cache object is reused between glob calls.
793
794Users are thus advised not to use a glob result as a guarantee of
795filesystem state in the face of rapid changes. For the vast
796majority of operations, this is never a problem.
797
798### See Also:
799
800- `man sh`
801- `man bash` [Pattern
802  Matching](https://www.gnu.org/software/bash/manual/html_node/Pattern-Matching.html)
803- `man 3 fnmatch`
804- `man 5 gitignore`
805- [minimatch documentation](https://github.com/isaacs/minimatch)
806
807## Glob Logo
808
809Glob's logo was created by [Tanya
810Brassie](http://tanyabrassie.com/). Logo files can be found
811[here](https://github.com/isaacs/node-glob/tree/master/logo).
812
813The logo is licensed under a [Creative Commons
814Attribution-ShareAlike 4.0 International
815License](https://creativecommons.org/licenses/by-sa/4.0/).
816
817## Contributing
818
819Any change to behavior (including bugfixes) must come with a
820test.
821
822Patches that fail tests or reduce performance will be rejected.
823
824```sh
825# to run tests
826npm test
827
828# to re-generate test fixtures
829npm run test-regen
830
831# run the benchmarks
832npm run bench
833
834# to profile javascript
835npm run prof
836```
837
838## Comparison to Other JavaScript Glob Implementations
839
840**tl;dr**
841
842- If you want glob matching that is as faithful as possible to
843  Bash pattern expansion semantics, and as fast as possible
844  within that constraint, _use this module_.
845- If you are reasonably sure that the patterns you will encounter
846  are relatively simple, and want the absolutely fastest glob
847  matcher out there, _use [fast-glob](http://npm.im/fast-glob)_.
848- If you are reasonably sure that the patterns you will encounter
849  are relatively simple, and want the convenience of
850  automatically respecting `.gitignore` files, _use
851  [globby](http://npm.im/globby)_.
852
853There are some other glob matcher libraries on npm, but these
854three are (in my opinion, as of 2023) the best.
855
856---
857
858**full explanation**
859
860Every library reflects a set of opinions and priorities in the
861trade-offs it makes. Other than this library, I can personally
862recommend both [globby](http://npm.im/globby) and
863[fast-glob](http://npm.im/fast-glob), though they differ in their
864benefits and drawbacks.
865
866Both have very nice APIs and are reasonably fast.
867
868`fast-glob` is, as far as I am aware, the fastest glob
869implementation in JavaScript today. However, there are many
870cases where the choices that `fast-glob` makes in pursuit of
871speed mean that its results differ from the results returned by
872Bash and other sh-like shells, which may be surprising.
873
874In my testing, `fast-glob` is around 10-20% faster than this
875module when walking over 200k files nested 4 directories
876deep[1](#fn-webscale). However, there are some inconsistencies
877with Bash matching behavior that this module does not suffer
878from:
879
880- `**` only matches files, not directories
881- `..` path portions are not handled unless they appear at the
882  start of the pattern
883- `./!(<pattern>)` will not match any files that _start_ with
884  `<pattern>`, even if they do not match `<pattern>`. For
885  example, `!(9).txt` will not match `9999.txt`.
886- Some brace patterns in the middle of a pattern will result in
887  failing to find certain matches.
888- Extglob patterns are allowed to contain `/` characters.
889
890Globby exhibits all of the same pattern semantics as fast-glob,
891(as it is a wrapper around fast-glob) and is slightly slower than
892node-glob (by about 10-20% in the benchmark test set, or in other
893words, anywhere from 20-50% slower than fast-glob). However, it
894adds some API conveniences that may be worth the costs.
895
896- Support for `.gitignore` and other ignore files.
897- Support for negated globs (ie, patterns starting with `!`
898  rather than using a separate `ignore` option).
899
900The priority of this module is "correctness" in the sense of
901performing a glob pattern expansion as faithfully as possible to
902the behavior of Bash and other sh-like shells, with as much speed
903as possible.
904
905Note that prior versions of `node-glob` are _not_ on this list.
906Former versions of this module are far too slow for any cases
907where performance matters at all, and were designed with APIs
908that are extremely dated by current JavaScript standards.
909
910---
911
912<small id="fn-webscale">[1]: In the cases where this module
913returns results and `fast-glob` doesn't, it's even faster, of
914course.</small>
915
916![lumpy space princess saying 'oh my GLOB'](https://github.com/isaacs/node-glob/raw/main/oh-my-glob.gif)
917
918### Benchmark Results
919
920First number is time, smaller is better.
921
922Second number is the count of results returned.
923
924```
925--- pattern: '**' ---
926~~ sync ~~
927node fast-glob sync             0m0.598s  200364
928node globby sync                0m0.765s  200364
929node current globSync mjs       0m0.683s  222656
930node current glob syncStream    0m0.649s  222656
931~~ async ~~
932node fast-glob async            0m0.350s  200364
933node globby async               0m0.509s  200364
934node current glob async mjs     0m0.463s  222656
935node current glob stream        0m0.411s  222656
936
937--- pattern: '**/..' ---
938~~ sync ~~
939node fast-glob sync             0m0.486s  0
940node globby sync                0m0.769s  200364
941node current globSync mjs       0m0.564s  2242
942node current glob syncStream    0m0.583s  2242
943~~ async ~~
944node fast-glob async            0m0.283s  0
945node globby async               0m0.512s  200364
946node current glob async mjs     0m0.299s  2242
947node current glob stream        0m0.312s  2242
948
949--- pattern: './**/0/**/0/**/0/**/0/**/*.txt' ---
950~~ sync ~~
951node fast-glob sync             0m0.490s  10
952node globby sync                0m0.517s  10
953node current globSync mjs       0m0.540s  10
954node current glob syncStream    0m0.550s  10
955~~ async ~~
956node fast-glob async            0m0.290s  10
957node globby async               0m0.296s  10
958node current glob async mjs     0m0.278s  10
959node current glob stream        0m0.302s  10
960
961--- pattern: './**/[01]/**/[12]/**/[23]/**/[45]/**/*.txt' ---
962~~ sync ~~
963node fast-glob sync             0m0.500s  160
964node globby sync                0m0.528s  160
965node current globSync mjs       0m0.556s  160
966node current glob syncStream    0m0.573s  160
967~~ async ~~
968node fast-glob async            0m0.283s  160
969node globby async               0m0.301s  160
970node current glob async mjs     0m0.306s  160
971node current glob stream        0m0.322s  160
972
973--- pattern: './**/0/**/0/**/*.txt' ---
974~~ sync ~~
975node fast-glob sync             0m0.502s  5230
976node globby sync                0m0.527s  5230
977node current globSync mjs       0m0.544s  5230
978node current glob syncStream    0m0.557s  5230
979~~ async ~~
980node fast-glob async            0m0.285s  5230
981node globby async               0m0.305s  5230
982node current glob async mjs     0m0.304s  5230
983node current glob stream        0m0.310s  5230
984
985--- pattern: '**/*.txt' ---
986~~ sync ~~
987node fast-glob sync             0m0.580s  200023
988node globby sync                0m0.771s  200023
989node current globSync mjs       0m0.685s  200023
990node current glob syncStream    0m0.649s  200023
991~~ async ~~
992node fast-glob async            0m0.349s  200023
993node globby async               0m0.509s  200023
994node current glob async mjs     0m0.427s  200023
995node current glob stream        0m0.388s  200023
996
997--- pattern: '{**/*.txt,**/?/**/*.txt,**/?/**/?/**/*.txt,**/?/**/?/**/?/**/*.txt,**/?/**/?/**/?/**/?/**/*.txt}' ---
998~~ sync ~~
999node fast-glob sync             0m0.589s  200023
1000node globby sync                0m0.771s  200023
1001node current globSync mjs       0m0.716s  200023
1002node current glob syncStream    0m0.684s  200023
1003~~ async ~~
1004node fast-glob async            0m0.351s  200023
1005node globby async               0m0.518s  200023
1006node current glob async mjs     0m0.462s  200023
1007node current glob stream        0m0.468s  200023
1008
1009--- pattern: '**/5555/0000/*.txt' ---
1010~~ sync ~~
1011node fast-glob sync             0m0.496s  1000
1012node globby sync                0m0.519s  1000
1013node current globSync mjs       0m0.539s  1000
1014node current glob syncStream    0m0.567s  1000
1015~~ async ~~
1016node fast-glob async            0m0.285s  1000
1017node globby async               0m0.299s  1000
1018node current glob async mjs     0m0.305s  1000
1019node current glob stream        0m0.301s  1000
1020
1021--- pattern: './**/0/**/../[01]/**/0/../**/0/*.txt' ---
1022~~ sync ~~
1023node fast-glob sync             0m0.484s  0
1024node globby sync                0m0.507s  0
1025node current globSync mjs       0m0.577s  4880
1026node current glob syncStream    0m0.586s  4880
1027~~ async ~~
1028node fast-glob async            0m0.280s  0
1029node globby async               0m0.298s  0
1030node current glob async mjs     0m0.327s  4880
1031node current glob stream        0m0.324s  4880
1032
1033--- pattern: '**/????/????/????/????/*.txt' ---
1034~~ sync ~~
1035node fast-glob sync             0m0.547s  100000
1036node globby sync                0m0.673s  100000
1037node current globSync mjs       0m0.626s  100000
1038node current glob syncStream    0m0.618s  100000
1039~~ async ~~
1040node fast-glob async            0m0.315s  100000
1041node globby async               0m0.414s  100000
1042node current glob async mjs     0m0.366s  100000
1043node current glob stream        0m0.345s  100000
1044
1045--- pattern: './{**/?{/**/?{/**/?{/**/?,,,,},,,,},,,,},,,}/**/*.txt' ---
1046~~ sync ~~
1047node fast-glob sync             0m0.588s  100000
1048node globby sync                0m0.670s  100000
1049node current globSync mjs       0m0.717s  200023
1050node current glob syncStream    0m0.687s  200023
1051~~ async ~~
1052node fast-glob async            0m0.343s  100000
1053node globby async               0m0.418s  100000
1054node current glob async mjs     0m0.519s  200023
1055node current glob stream        0m0.451s  200023
1056
1057--- pattern: '**/!(0|9).txt' ---
1058~~ sync ~~
1059node fast-glob sync             0m0.573s  160023
1060node globby sync                0m0.731s  160023
1061node current globSync mjs       0m0.680s  180023
1062node current glob syncStream    0m0.659s  180023
1063~~ async ~~
1064node fast-glob async            0m0.345s  160023
1065node globby async               0m0.476s  160023
1066node current glob async mjs     0m0.427s  180023
1067node current glob stream        0m0.388s  180023
1068
1069--- pattern: './{*/**/../{*/**/../{*/**/../{*/**/../{*/**,,,,},,,,},,,,},,,,},,,,}/*.txt' ---
1070~~ sync ~~
1071node fast-glob sync             0m0.483s  0
1072node globby sync                0m0.512s  0
1073node current globSync mjs       0m0.811s  200023
1074node current glob syncStream    0m0.773s  200023
1075~~ async ~~
1076node fast-glob async            0m0.280s  0
1077node globby async               0m0.299s  0
1078node current glob async mjs     0m0.617s  200023
1079node current glob stream        0m0.568s  200023
1080
1081--- pattern: './*/**/../*/**/../*/**/../*/**/../*/**/../*/**/../*/**/../*/**/*.txt' ---
1082~~ sync ~~
1083node fast-glob sync             0m0.485s  0
1084node globby sync                0m0.507s  0
1085node current globSync mjs       0m0.759s  200023
1086node current glob syncStream    0m0.740s  200023
1087~~ async ~~
1088node fast-glob async            0m0.281s  0
1089node globby async               0m0.297s  0
1090node current glob async mjs     0m0.544s  200023
1091node current glob stream        0m0.464s  200023
1092
1093--- pattern: './*/**/../*/**/../*/**/../*/**/../*/**/*.txt' ---
1094~~ sync ~~
1095node fast-glob sync             0m0.486s  0
1096node globby sync                0m0.513s  0
1097node current globSync mjs       0m0.734s  200023
1098node current glob syncStream    0m0.696s  200023
1099~~ async ~~
1100node fast-glob async            0m0.286s  0
1101node globby async               0m0.296s  0
1102node current glob async mjs     0m0.506s  200023
1103node current glob stream        0m0.483s  200023
1104
1105--- pattern: './0/**/../1/**/../2/**/../3/**/../4/**/../5/**/../6/**/../7/**/*.txt' ---
1106~~ sync ~~
1107node fast-glob sync             0m0.060s  0
1108node globby sync                0m0.074s  0
1109node current globSync mjs       0m0.067s  0
1110node current glob syncStream    0m0.066s  0
1111~~ async ~~
1112node fast-glob async            0m0.060s  0
1113node globby async               0m0.075s  0
1114node current glob async mjs     0m0.066s  0
1115node current glob stream        0m0.067s  0
1116
1117--- pattern: './**/?/**/?/**/?/**/?/**/*.txt' ---
1118~~ sync ~~
1119node fast-glob sync             0m0.568s  100000
1120node globby sync                0m0.651s  100000
1121node current globSync mjs       0m0.619s  100000
1122node current glob syncStream    0m0.617s  100000
1123~~ async ~~
1124node fast-glob async            0m0.332s  100000
1125node globby async               0m0.409s  100000
1126node current glob async mjs     0m0.372s  100000
1127node current glob stream        0m0.351s  100000
1128
1129--- pattern: '**/*/**/*/**/*/**/*/**' ---
1130~~ sync ~~
1131node fast-glob sync             0m0.603s  200113
1132node globby sync                0m0.798s  200113
1133node current globSync mjs       0m0.730s  222137
1134node current glob syncStream    0m0.693s  222137
1135~~ async ~~
1136node fast-glob async            0m0.356s  200113
1137node globby async               0m0.525s  200113
1138node current glob async mjs     0m0.508s  222137
1139node current glob stream        0m0.455s  222137
1140
1141--- pattern: './**/*/**/*/**/*/**/*/**/*.txt' ---
1142~~ sync ~~
1143node fast-glob sync             0m0.622s  200000
1144node globby sync                0m0.792s  200000
1145node current globSync mjs       0m0.722s  200000
1146node current glob syncStream    0m0.695s  200000
1147~~ async ~~
1148node fast-glob async            0m0.369s  200000
1149node globby async               0m0.527s  200000
1150node current glob async mjs     0m0.502s  200000
1151node current glob stream        0m0.481s  200000
1152
1153--- pattern: '**/*.txt' ---
1154~~ sync ~~
1155node fast-glob sync             0m0.588s  200023
1156node globby sync                0m0.771s  200023
1157node current globSync mjs       0m0.684s  200023
1158node current glob syncStream    0m0.658s  200023
1159~~ async ~~
1160node fast-glob async            0m0.352s  200023
1161node globby async               0m0.516s  200023
1162node current glob async mjs     0m0.432s  200023
1163node current glob stream        0m0.384s  200023
1164
1165--- pattern: './**/**/**/**/**/**/**/**/*.txt' ---
1166~~ sync ~~
1167node fast-glob sync             0m0.589s  200023
1168node globby sync                0m0.766s  200023
1169node current globSync mjs       0m0.682s  200023
1170node current glob syncStream    0m0.652s  200023
1171~~ async ~~
1172node fast-glob async            0m0.352s  200023
1173node globby async               0m0.523s  200023
1174node current glob async mjs     0m0.436s  200023
1175node current glob stream        0m0.380s  200023
1176
1177--- pattern: '**/*/*.txt' ---
1178~~ sync ~~
1179node fast-glob sync             0m0.592s  200023
1180node globby sync                0m0.776s  200023
1181node current globSync mjs       0m0.691s  200023
1182node current glob syncStream    0m0.659s  200023
1183~~ async ~~
1184node fast-glob async            0m0.357s  200023
1185node globby async               0m0.513s  200023
1186node current glob async mjs     0m0.471s  200023
1187node current glob stream        0m0.424s  200023
1188
1189--- pattern: '**/*/**/*.txt' ---
1190~~ sync ~~
1191node fast-glob sync             0m0.585s  200023
1192node globby sync                0m0.766s  200023
1193node current globSync mjs       0m0.694s  200023
1194node current glob syncStream    0m0.664s  200023
1195~~ async ~~
1196node fast-glob async            0m0.350s  200023
1197node globby async               0m0.514s  200023
1198node current glob async mjs     0m0.472s  200023
1199node current glob stream        0m0.424s  200023
1200
1201--- pattern: '**/[0-9]/**/*.txt' ---
1202~~ sync ~~
1203node fast-glob sync             0m0.544s  100000
1204node globby sync                0m0.636s  100000
1205node current globSync mjs       0m0.626s  100000
1206node current glob syncStream    0m0.621s  100000
1207~~ async ~~
1208node fast-glob async            0m0.322s  100000
1209node globby async               0m0.404s  100000
1210node current glob async mjs     0m0.360s  100000
1211node current glob stream        0m0.352s  100000
1212```
1213