MCPcopy Index your code
hub / github.com/isaacs/node-glob

github.com/isaacs/node-glob @v13.0.6 sqlite

repository ↗ · DeepWiki ↗ · release v13.0.6 ↗
131 symbols 393 edges 53 files 16 documented · 12%
README

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

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.

// 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 fs.Dirent, but with some more added powers
// check out https://isaacs.github.io/path-scurry/classes/PathBase.html
// 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

The glob CLI has been moved to the glob-bin package, and must be installed separately, as of version 13.

npm install glob-bin

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

Perform an asynchronous glob search for the pattern(s) specified. Returns Path 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] 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).

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.

[!NOTE] 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.

  • windowsPathsNoEscape Use \\ as a path separator only, and never as an escape character. If set, all \\ characters are replaced with / in the pattern.

[!NOTE] 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. (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.

As a shortcut to avoid excessive RegExp creations, Glob will use string portions as-is to readdir() calls while doing its traversal. If you are setting a nocase: true match on a file system that is in fact case sensitive, then this will result in matches not being found that you might expect, because for example the pattern Foo/* will fail to read the FOO/ or foo/ directories.

On the other hand, if you set nocase: false on a case-insensitive system, then the opposite problem occurs: Foo/* will match foo/bar, but because we only detect the existence of the foo/ folder by successfully performing a readdir, there's no way to know what the "real" case is, and the match will be reported as Foo/bar, using the case of the string portion of the glob pattern.

The default is usually correct, however it is possible to mount file systems with a different case-sensitivity from the host system. If you know this is the case, set this flag appropria

Extension points exported contracts — how you extend this code

IgnoreLike (Interface)
(no doc) [1 implementers]
src/ignore.ts
GlobOptions (Interface)
(no doc) [1 implementers]
src/glob.ts
GlobWalkerOpts (Interface)
(no doc)
src/walker.ts

Core symbols most depended-on inside this repo

j
called by 28
test/ignore.ts
globSync
called by 17
src/index.ts
add
called by 17
src/processor.ts
j
called by 12
test/mark.ts
walkSync
called by 11
src/glob.ts
j
called by 10
test/match-base.ts
entries
called by 10
src/processor.ts
walk
called by 9
src/glob.ts

Shape

Function 55
Method 54
Class 19
Interface 3

Languages

TypeScript100%

Modules by API surface

src/walker.ts34 symbols
src/processor.ts26 symbols
src/pattern.ts19 symbols
src/glob.ts12 symbols
src/ignore.ts7 symbols
src/index.ts6 symbols
test/00-setup.ts3 symbols
scripts/make-big-tree.js3 symbols
test/root.ts2 symbols
test/nodir.ts2 symbols
test/match-base.ts2 symbols
test/mark.ts2 symbols

Dependencies from manifests, versioned

@types/node25.3.0 · 1×
esbuild0.27.3 · 1×
memfs4.50.0 · 1×
minimatch10.2.2 · 1×
minipass7.1.3 · 1×
mkdirp3.0.1 · 1×
path-scurry2.0.2 · 1×
prettier3.6.2 · 1×
rimraf6.1.3 · 1×
tap21.6.1 · 1×
tshy3.3.2 · 1×
typedoc0.28.17 · 1×

For agents

$ claude mcp add node-glob \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact