# Glob

Match files using the patterns the shell uses.

The most correct and second fastest glob implementation in
JavaScript. (See **Comparison to Other JavaScript Glob
Implementations** at the bottom of this readme.)

![a fun cartoon logo made of glob characters](https://github.com/isaacs/node-glob/raw/main/logo/glob.png)

## Usage

Install with npm

```
npm i glob
```

**Note** the npm package name is _not_ `node-glob` that's a
different thing that was abandoned years ago. Just `glob`.

```js
// load using import
import { glob, globSync, globStream, globStreamSync, Glob } from 'glob'
// or using commonjs, that's fine, too
const {
  glob,
  globSync,
  globStream,
  globStreamSync,
  Glob,
} = require('glob')

// the main glob() and globSync() resolve/return array of filenames

// all js files, but don't look in node_modules
const jsfiles = await glob('**/*.js', { ignore: 'node_modules/**' })

// pass in a signal to cancel the glob walk
const stopAfter100ms = await glob('**/*.css', {
  signal: AbortSignal.timeout(100),
})

// multiple patterns supported as well
const images = await glob(['css/*.{png,jpeg}', 'public/*.{png,jpeg}'])

// but of course you can do that with the glob pattern also
// the sync function is the same, just returns a string[] instead
// of Promise<string[]>
const imagesAlt = globSync('{css,public}/*.{png,jpeg}')

// you can also stream them, this is a Minipass stream
const filesStream = globStream(['**/*.dat', 'logs/**/*.log'])

// construct a Glob object if you wanna do it that way, which
// allows for much faster walks if you have to look in the same
// folder multiple times.
const g = new Glob('**/foo', {})
// glob objects are async iterators, can also do globIterate() or
// g.iterate(), same deal
for await (const file of g) {
  console.log('found a foo file:', file)
}
// pass a glob as the glob options to reuse its settings and caches
const g2 = new Glob('**/bar', g)
// sync iteration works as well
for (const file of g2) {
  console.log('found a bar file:', file)
}

// you can also pass withFileTypes: true to get Path objects
// these are like a Dirent, but with some more added powers
// check out http://npm.im/path-scurry for more info on their API
const g3 = new Glob('**/baz/**', { withFileTypes: true })
g3.stream().on('data', path => {
  console.log(
    'got a path object',
    path.fullpath(),
    path.isDirectory(),
    path.readdirSync().map(e => e.name),
  )
})

// if you use stat:true and withFileTypes, you can sort results
// by things like modified time, filter by permission mode, etc.
// All Stats fields will be available in that case. Slightly
// slower, though.
// For example:
const results = await glob('**', { stat: true, withFileTypes: true })

const timeSortedFiles = results
  .sort((a, b) => a.mtimeMs - b.mtimeMs)
  .map(path => path.fullpath())

const groupReadableFiles = results
  .filter(path => path.mode & 0o040)
  .map(path => path.fullpath())

// custom ignores can be done like this, for example by saying
// you'll ignore all markdown files, and all folders named 'docs'
const customIgnoreResults = await glob('**', {
  ignore: {
    ignored: p => /\.md$/.test(p.name),
    childrenIgnored: p => p.isNamed('docs'),
  },
})

// another fun use case, only return files with the same name as
// their parent folder, plus either `.ts` or `.js`
const folderNamedModules = await glob('**/*.{ts,js}', {
  ignore: {
    ignored: p => {
      const pp = p.parent
      return !(p.isNamed(pp.name + '.ts') || p.isNamed(pp.name + '.js'))
    },
  },
})

// find all files edited in the last hour, to do this, we ignore
// all of them that are more than an hour old
const newFiles = await glob('**', {
  // need stat so we have mtime
  stat: true,
  // only want the files, not the dirs
  nodir: true,
  ignore: {
    ignored: p => {
      return new Date() - p.mtime > 60 * 60 * 1000
    },
    // could add similar childrenIgnored here as well, but
    // directory mtime is inconsistent across platforms, so
    // probably better not to, unless you know the system
    // tracks this reliably.
  },
})
```

**Note** Glob patterns should always use `/` as a path separator,
even on Windows systems, as `\` is used to escape glob
characters. If you wish to use `\` as a path separator _instead
of_ using it as an escape character on Windows platforms, you may
set `windowsPathsNoEscape:true` in the options. In this mode,
special glob characters cannot be escaped, making it impossible
to match a literal `*` `?` and so on in filenames.

## Command Line Interface

```
$ glob -h

Usage:
  glob [options] [<pattern> [<pattern> ...]]

Expand the positional glob expression arguments into any matching file system
paths found.

  -c<command> --cmd=<command>
                         Run the command provided, passing the glob expression
                         matches as arguments.

  -A --all               By default, the glob cli command will not expand any
                         arguments that are an exact match to a file on disk.

                         This prevents double-expanding, in case the shell
                         expands an argument whose filename is a glob
                         expression.

                         For example, if 'app/*.ts' would match 'app/[id].ts',
                         then on Windows powershell or cmd.exe, 'glob app/*.ts'
                         will expand to 'app/[id].ts', as expected. However, in
                         posix shells such as bash or zsh, the shell will first
                         expand 'app/*.ts' to a list of filenames. Then glob
                         will look for a file matching 'app/[id].ts' (ie,
                         'app/i.ts' or 'app/d.ts'), which is unexpected.

                         Setting '--all' prevents this behavior, causing glob to
                         treat ALL patterns as glob expressions to be expanded,
                         even if they are an exact match to a file on disk.

                         When setting this option, be sure to enquote arguments
                         so that the shell will not expand them prior to passing
                         them to the glob command process.

  -a --absolute          Expand to absolute paths
  -d --dot-relative      Prepend './' on relative matches
  -m --mark              Append a / on any directories matched
  -x --posix             Always resolve to posix style paths, using '/' as the
                         directory separator, even on Windows. Drive letter
                         absolute matches on Windows will be expanded to their
                         full resolved UNC maths, eg instead of 'C:\foo\bar', it
                         will expand to '//?/C:/foo/bar'.

  -f --follow            Follow symlinked directories when expanding '**'
  -R --realpath          Call 'fs.realpath' on all of the results. In the case
                         of an entry that cannot be resolved, the entry is
                         omitted. This incurs a slight performance penalty, of
                         course, because of the added system calls.

  -s --stat              Call 'fs.lstat' on all entries, whether required or not
                         to determine if it's a valid match.

  -b --match-base        Perform a basename-only match if the pattern does not
                         contain any slash characters. That is, '*.js' would be
                         treated as equivalent to '**/*.js', matching js files
                         in all directories.

  --dot                  Allow patterns to match files/directories that start
                         with '.', even if the pattern does not start with '.'

  --nobrace              Do not expand {...} patterns
  --nocase               Perform a case-insensitive match. This defaults to
                         'true' on macOS and Windows platforms, and false on all
                         others.

                         Note: 'nocase' should only be explicitly set when it is
                         known that the filesystem's case sensitivity differs
                         from the platform default. If set 'true' on
                         case-insensitive file systems, then the walk may return
                         more or less results than expected.

  --nodir                Do not match directories, only files.

                         Note: to *only* match directories, append a '/' at the
                         end of the pattern.

  --noext                Do not expand extglob patterns, such as '+(a|b)'
  --noglobstar           Do not expand '**' against multiple path portions. Ie,
                         treat it as a normal '*' instead.

  --windows-path-no-escape
                         Use '\' as a path separator *only*, and *never* as an
                         escape character. If set, all '\' characters are
                         replaced with '/' in the pattern.

  -D<n> --max-depth=<n>  Maximum depth to traverse from the current working
                         directory

  -C<cwd> --cwd=<cwd>    Current working directory to execute/match in
  -r<root> --root=<root> A string path resolved against the 'cwd', which is used
                         as the starting point for absolute patterns that start
                         with '/' (but not drive letters or UNC paths on
                         Windows).

                         Note that this *doesn't* necessarily limit the walk to
                         the 'root' directory, and doesn't affect the cwd
                         starting point for non-absolute patterns. A pattern
                         containing '..' will still be able to traverse out of
                         the root directory, if it is not an actual root
                         directory on the filesystem, and any non-absolute
                         patterns will still be matched in the 'cwd'.

                         To start absolute and non-absolute patterns in the same
                         path, you can use '--root=' to set it to the empty
                         string. However, be aware that on Windows systems, a
                         pattern like 'x:/*' or '//host/share/*' will *always*
                         start in the 'x:/' or '//host/share/' directory,
                         regardless of the --root setting.

  --platform=<platform>  Defaults to the value of 'process.platform' if
                         available, or 'linux' if not. Setting --platform=win32
                         on non-Windows systems may cause strange behavior!

  -i<ignore> --ignore=<ignore>
                         Glob patterns to ignore Can be set multiple times
  -v --debug             Output a huge amount of noisy debug information about
                         patterns as they are parsed and used to match files.

  -h --help              Show this usage information
```

## `glob(pattern: string | string[], options?: GlobOptions) => Promise<string[] | Path[]>`

Perform an asynchronous glob search for the pattern(s) specified.
Returns
[Path](https://isaacs.github.io/path-scurry/classes/PathBase)
objects if the `withFileTypes` option is set to `true`. See below
for full options field desciptions.

## `globSync(pattern: string | string[], options?: GlobOptions) => string[] | Path[]`

Synchronous form of `glob()`.

Alias: `glob.sync()`

## `globIterate(pattern: string | string[], options?: GlobOptions) => AsyncGenerator<string>`

Return an async iterator for walking glob pattern matches.

Alias: `glob.iterate()`

## `globIterateSync(pattern: string | string[], options?: GlobOptions) => Generator<string>`

Return a sync iterator for walking glob pattern matches.

Alias: `glob.iterate.sync()`, `glob.sync.iterate()`

## `globStream(pattern: string | string[], options?: GlobOptions) => Minipass<string | Path>`

Return a stream that emits all the strings or `Path` objects and
then emits `end` when completed.

Alias: `glob.stream()`

## `globStreamSync(pattern: string | string[], options?: GlobOptions) => Minipass<string | Path>`

Syncronous form of `globStream()`. Will read all the matches as
fast as you consume them, even all in a single tick if you
consume them immediately, but will still respond to backpressure
if they're not consumed immediately.

Alias: `glob.stream.sync()`, `glob.sync.stream()`

## `hasMagic(pattern: string | string[], options?: GlobOptions) => boolean`

Returns `true` if the provided pattern contains any "magic" glob
characters, given the options provided.

Brace expansion is not considered "magic" unless the
`magicalBraces` option is set, as brace expansion just turns one
string into an array of strings. So a pattern like `'x{a,b}y'`
would return `false`, because `'xay'` and `'xby'` both do not
contain any magic glob characters, and it's treated the same as
if you had called it on `['xay', 'xby']`. When
`magicalBraces:true` is in the options, brace expansion _is_
treated as a pattern having magic.

## `escape(pattern: string, options?: GlobOptions) => string`

Escape all magic characters in a glob pattern, so that it will
only ever match literal strings

If the `windowsPathsNoEscape` option is used, then characters are
escaped by wrapping in `[]`, because a magic character wrapped in
a character class can only be satisfied by that exact character.

Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot
be escaped or unescaped.

## `unescape(pattern: string, options?: GlobOptions) => string`

Un-escape a glob string that may contain some escaped characters.

If the `windowsPathsNoEscape` option is used, then square-brace
escapes are removed, but not backslash escapes. For example, it
will turn the string `'[*]'` into `*`, but it will not turn
`'\\*'` into `'*'`, because `\` is a path separator in
`windowsPathsNoEscape` mode.

When `windowsPathsNoEscape` is not set, then both brace escapes
and backslash escapes are removed.

Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot
be escaped or unescaped.

## Class `Glob`

An object that can perform glob pattern traversals.

### `const g = new Glob(pattern: string | string[], options: GlobOptions)`

Options object is required.

See full options descriptions below.

Note that a previous `Glob` object can be passed as the
`GlobOptions` to another `Glob` instantiation to re-use settings
and caches with a new pattern.

Traversal functions can be called multiple times to run the walk
again.

### `g.stream()`

Stream results asynchronously,

### `g.streamSync()`

Stream results synchronously.

### `g.iterate()`

Default async iteration function. Returns an AsyncGenerator that
iterates over the results.

### `g.iterateSync()`

Default sync iteration function. Returns a Generator that
iterates over the results.

### `g.walk()`

Returns a Promise that resolves to the results array.

### `g.walkSync()`

Returns a results array.

### Properties

All options are stored as properties on the `Glob` object.

- `opts` The options provided to the constructor.
- `patterns` An array of parsed immutable `Pattern` objects.

## Options

Exported as `GlobOptions` TypeScript interface. A `GlobOptions`
object may be provided to any of the exported methods, and must
be provided to the `Glob` constructor.

All options are optional, boolean, and false by default, unless
otherwise noted.

All resolved options are added to the Glob object as properties.

If you are running many `glob` operations, you can pass a Glob
object as the `options` argument to a subsequent operation to
share the previously loaded cache.

- `cwd` String path or `file://` string or URL object. The
  current working directory in which to search. Defaults to
  `process.cwd()`. See also: "Windows, CWDs, Drive Letters, and
  UNC Paths", below.

  This option may be either a string path or a `file://` URL
  object or string.

- `root` A string path resolved against the `cwd` option, which
  is used as the starting point for absolute patterns that start
  with `/`, (but not drive letters or UNC paths on Windows).

  Note that this _doesn't_ necessarily limit the walk to the
  `root` directory, and doesn't affect the cwd starting point for
  non-absolute patterns. A pattern containing `..` will still be
  able to traverse out of the root directory, if it is not an
  actual root directory on the filesystem, and any non-absolute
  patterns will be matched in the `cwd`. For example, the
  pattern `/../*` with `{root:'/some/path'}` will return all
  files in `/some`, not all files in `/some/path`. The pattern
  `*` with `{root:'/some/path'}` will return all the entries in
  the cwd, not the entries in `/some/path`.

  To start absolute and non-absolute patterns in the same
  path, you can use `{root:''}`. However, be aware that on
  Windows systems, a pattern like `x:/*` or `//host/share/*` will
  _always_ start in the `x:/` or `//host/share` directory,
  regardless of the `root` setting.

- `windowsPathsNoEscape` Use `\\` as a path separator _only_, and
  _never_ as an escape character. If set, all `\\` characters are
  replaced with `/` in the pattern.

  Note that this makes it **impossible** to match against paths
  containing literal glob pattern characters, but allows matching
  with patterns constructed using `path.join()` and
  `path.resolve()` on Windows platforms, mimicking the (buggy!)
  behavior of Glob v7 and before on Windows. Please use with
  caution, and be mindful of [the caveat below about Windows
  paths](#windows). (For legacy reasons, this is also set if
  `allowWindowsEscape` is set to the exact value `false`.)

- `dot` Include `.dot` files in normal matches and `globstar`
  matches. Note that an explicit dot in a portion of the pattern
  will always match dot files.

- `magicalBraces` Treat brace expansion like `{a,b}` as a "magic"
  pattern. Has no effect if {@link nobrace} is set.

  Only has effect on the {@link hasMagic} function, no effect on
  glob pattern matching itself.

- `dotRelative` Prepend all relative path strings with `./` (or
  `.\` on Windows).

  Without this option, returned relative paths are "bare", so
  instead of returning `'./foo/bar'`, they are returned as
  `'foo/bar'`.

  Relative patterns starting with `'../'` are not prepended with
  `./`, even if this option is set.

- `mark` Add a `/` character to directory matches. Note that this
  requires additional stat calls.

- `nobrace` Do not expand `{a,b}` and `{1..3}` brace sets.

- `noglobstar` Do not match `**` against multiple filenames. (Ie,
  treat it as a normal `*` instead.)

- `noext` Do not match "extglob" patterns such as `+(a|b)`.

- `nocase` Perform a case-insensitive match. This defaults to
  `true` on macOS and Windows systems, and `false` on all others.

  **Note** `nocase` should only be explicitly set when it is
  known that the filesystem's case sensitivity differs from the
  platform default. If set `true` on case-sensitive file
  systems, or `false` on case-insensitive file systems, then the
  walk may return more or less results than expected.

- `maxDepth` Specify a number to limit the depth of the directory
  traversal to this many levels below the `cwd`.

- `matchBase` Perform a basename-only match if the pattern does
  not contain any slash characters. That is, `*.js` would be
  treated as equivalent to `**/*.js`, matching all js files in
  all directories.

- `nodir` Do not match directories, only files. (Note: to match
  _only_ directories, put a `/` at the end of the pattern.)

  Note: when `follow` and `nodir` are both set, then symbolic
  links to directories are also omitted.

- `stat` Call `lstat()` on all entries, whether required or not
  to determine whether it's a valid match. When used with
  `withFileTypes`, this means that matches will include data such
  as modified time, permissions, and so on. Note that this will
  incur a performance cost due to the added system calls.

- `ignore` string or string[], or an object with `ignore` and
  `ignoreChildren` methods.

  If a string or string[] is provided, then this is treated as a
  glob pattern or array of glob patterns to exclude from matches.
  To ignore all children within a directory, as well as the entry
  itself, append `'/**'` to the ignore pattern.

  **Note** `ignore` patterns are _always_ in `dot:true` mode,
  regardless of any other settings.

  If an object is provided that has `ignored(path)` and/or
  `childrenIgnored(path)` methods, then these methods will be
  called to determine whether any Path is a match or if its
  children should be traversed, respectively.

- `follow` Follow symlinked directories when expanding `**`
  patterns. This can result in a lot of duplicate references in
  the presence of cyclic links, and make performance quite bad.

  By default, a `**` in a pattern will follow 1 symbolic link if
  it is not the first item in the pattern, or none if it is the
  first item in the pattern, following the same behavior as Bash.

  Note: when `follow` and `nodir` are both set, then symbolic
  links to directories are also omitted.

- `realpath` Set to true to call `fs.realpath` on all of the
  results. In the case of an entry that cannot be resolved, the
  entry is omitted. This incurs a slight performance penalty, of
  course, because of the added system calls.

- `absolute` Set to true to always receive absolute paths for
  matched files. Set to `false` to always receive relative paths
  for matched files.

  By default, when this option is not set, absolute paths are
  returned for patterns that are absolute, and otherwise paths
  are returned that are relative to the `cwd` setting.

  This does _not_ make an extra system call to get the realpath,
  it only does string path resolution.

  `absolute` may not be used along with `withFileTypes`.

- `posix` Set to true to use `/` as the path separator in
  returned results. On posix systems, this has no effect. On
  Windows systems, this will return `/` delimited path results,
  and absolute paths will be returned in their full resolved UNC
  path form, eg insted of `'C:\\foo\\bar'`, it will return
  `//?/C:/foo/bar`.

- `platform` Defaults to value of `process.platform` if
  available, or `'linux'` if not. Setting `platform:'win32'` on
  non-Windows systems may cause strange behavior.

- `withFileTypes` Return [PathScurry](http://npm.im/path-scurry)
  `Path` objects instead of strings. These are similar to a
  NodeJS `Dirent` object, but with additional methods and
  properties.

  `withFileTypes` may not be used along with `absolute`.

- `signal` An AbortSignal which will cancel the Glob walk when
  triggered.

- `fs` An override object to pass in custom filesystem methods.
  See [PathScurry docs](http://npm.im/path-scurry) for what can
  be overridden.

- `scurry` A 