Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

glob functionality for node.js

License

NotificationsYou must be signed in to change notification settings

isaacs/node-glob

Repository files navigation

Match files using the patterns the shell uses.

The most correct and second fastest glob implementation inJavaScript. (SeeComparison to Other JavaScript GlobImplementations 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 isnotnode-glob that's adifferent thing that was abandoned years ago. Justglob.

// load using importimport{glob,globSync,globStream,globStreamSync,Glob}from'glob'// or using commonjs, that's fine, tooconst{  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_modulesconstjsfiles=awaitglob('**/*.js',{ignore:'node_modules/**'})// pass in a signal to cancel the glob walkconststopAfter100ms=awaitglob('**/*.css',{signal:AbortSignal.timeout(100),})// multiple patterns supported as wellconstimages=awaitglob(['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[]>constimagesAlt=globSync('{css,public}/*.{png,jpeg}')// you can also stream them, this is a Minipass streamconstfilesStream=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.constg=newGlob('**/foo',{})// glob objects are async iterators, can also do globIterate() or// g.iterate(), same dealforawait(constfileofg){console.log('found a foo file:',file)}// pass a glob as the glob options to reuse its settings and cachesconstg2=newGlob('**/bar',g)// sync iteration works as wellfor(constfileofg2){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 APIconstg3=newGlob('**/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:constresults=awaitglob('**',{stat:true,withFileTypes:true})consttimeSortedFiles=results.sort((a,b)=>a.mtimeMs-b.mtimeMs).map(path=>path.fullpath())constgroupReadableFiles=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'constcustomIgnoreResults=awaitglob('**',{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`constfolderNamedModules=awaitglob('**/*.{ts,js}',{ignore:{ignored:p=>{constpp=p.parentreturn!(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 oldconstnewFiles=awaitglob('**',{// need stat so we have mtimestat:true,// only want the files, not the dirsnodir:true,ignore:{ignored:p=>{returnnewDate()-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 globcharacters. If you wish to use\ as a path separatorinsteadof using it as an escape character on Windows platforms, you maysetwindowsPathsNoEscape:true in the options. In this mode,special glob characters cannot be escaped, making it impossibleto match a literal*? and so on in filenames.

Command Line Interface

$ glob -hUsage:  glob [options] [<pattern> [<pattern> ...]]Expand the positional glob expression arguments into any matching file systempaths 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.ReturnsPathobjects if thewithFileTypes option is set totrue. See belowfor full options field desciptions.

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

Synchronous form ofglob().

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 orPath objects andthen emitsend when completed.

Alias:glob.stream()

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

Syncronous form ofglobStream(). Will read all the matches asfast as you consume them, even all in a single tick if youconsume them immediately, but will still respond to backpressureif they're not consumed immediately.

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

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

Returnstrue if the provided pattern contains any "magic" globcharacters, given the options provided.

Brace expansion is not considered "magic" unless themagicalBraces option is set, as brace expansion just turns onestring into an array of strings. So a pattern like'x{a,b}y'would returnfalse, because'xay' and'xby' both do notcontain any magic glob characters, and it's treated the same asif you had called it on['xay', 'xby']. WhenmagicalBraces:true is in the options, brace expansionistreated as a pattern having magic.

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

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

If thewindowsPathsNoEscape option is used, then characters areescaped by wrapping in[], because a magic character wrapped ina character class can only be satisfied by that exact character.

Slashes (and backslashes inwindowsPathsNoEscape mode) cannotbe escaped or unescaped.

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

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

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

WhenwindowsPathsNoEscape is not set, then both brace escapesand backslash escapes are removed.

Slashes (and backslashes inwindowsPathsNoEscape mode) cannotbe escaped or unescaped.

ClassGlob

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 previousGlob object can be passed as theGlobOptions to anotherGlob instantiation to re-use settingsand caches with a new pattern.

Traversal functions can be called multiple times to run the walkagain.

g.stream()

Stream results asynchronously,

g.streamSync()

Stream results synchronously.

g.iterate()

Default async iteration function. Returns an AsyncGenerator thatiterates over the results.

g.iterateSync()

Default sync iteration function. Returns a Generator thatiterates 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 theGlob object.

  • opts The options provided to the constructor.
  • patterns An array of parsed immutablePattern objects.

Options

Exported asGlobOptions TypeScript interface. AGlobOptionsobject may be provided to any of the exported methods, and mustbe provided to theGlob constructor.

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

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

If you are running manyglob operations, you can pass a Globobject as theoptions argument to a subsequent operation toshare the previously loaded cache.

  • cwd String path orfile:// string or URL object. Thecurrent working directory in which to search. Defaults toprocess.cwd(). See also: "Windows, CWDs, Drive Letters, andUNC Paths", below.

    This option may be either a string path or afile:// URLobject or string.

  • root A string path resolved against thecwd option, whichis used as the starting point for absolute patterns that startwith/, (but not drive letters or UNC paths on Windows).

    Note that thisdoesn't necessarily limit the walk to theroot directory, and doesn't affect the cwd starting point fornon-absolute patterns. A pattern containing.. will still beable to traverse out of the root directory, if it is not anactual root directory on the filesystem, and any non-absolutepatterns will be matched in thecwd. For example, thepattern/../* with{root:'/some/path'} will return allfiles in/some, not all files in/some/path. The pattern* with{root:'/some/path'} will return all the entries inthe cwd, not the entries in/some/path.

    To start absolute and non-absolute patterns in the samepath, you can use{root:''}. However, be aware that onWindows systems, a pattern likex:/* or//host/share/* willalways start in thex:/ or//host/share directory,regardless of theroot setting.

  • windowsPathsNoEscape Use\\ as a path separatoronly, andnever as an escape character. If set, all\\ characters arereplaced with/ in the pattern.

    Note that this makes itimpossible to match against pathscontaining literal glob pattern characters, but allows matchingwith patterns constructed usingpath.join() andpath.resolve() on Windows platforms, mimicking the (buggy!)behavior of Glob v7 and before on Windows. Please use withcaution, and be mindful ofthe caveat below about Windowspaths. (For legacy reasons, this is also set ifallowWindowsEscape is set to the exact valuefalse.)

  • dot Include.dot files in normal matches andglobstarmatches. Note that an explicit dot in a portion of the patternwill 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 onglob pattern matching itself.

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

    Without this option, returned relative paths are "bare", soinstead 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 thisrequires 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 totrue on macOS and Windows systems, andfalse on all others.

    Notenocase should only be explicitly set when it isknown that the filesystem's case sensitivity differs from theplatform default. If settrue on case-sensitive filesystems, orfalse on case-insensitive file systems, then thewalk may return more or less results than expected.

  • maxDepth Specify a number to limit the depth of the directorytraversal to this many levels below thecwd.

  • matchBase Perform a basename-only match if the pattern doesnot contain any slash characters. That is,*.js would betreated as equivalent to**/*.js, matching all js files inall directories.

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

    Note: whenfollow andnodir are both set, then symboliclinks to directories are also omitted.

  • stat Calllstat() on all entries, whether required or notto determine whether it's a valid match. When used withwithFileTypes, this means that matches will include data suchas modified time, permissions, and so on. Note that this willincur a performance cost due to the added system calls.

  • ignore string or string[], or an object withignored andchildrenIgnored methods.

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

    Noteignore patterns arealways indot:true mode,regardless of any other settings.

    If an object is provided that hasignored(path) and/orchildrenIgnored(path) methods, then these methods will becalled to determine whether any Path is a match or if itschildren should be traversed, respectively.

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

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

    Note: whenfollow andnodir are both set, then symboliclinks to directories are also omitted.

  • realpath Set to true to callfs.realpath on all of theresults. In the case of an entry that cannot be resolved, theentry is omitted. This incurs a slight performance penalty, ofcourse, because of the added system calls.

  • absolute Set to true to always receive absolute paths formatched files. Set tofalse to always receive relative pathsfor matched files.

    By default, when this option is not set, absolute paths arereturned for patterns that are absolute, and otherwise pathsare returned that are relative to thecwd setting.

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

    absolute may not be used along withwithFileTypes.

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

  • platform Defaults to value ofprocess.platform ifavailable, or'linux' if not. Settingplatform:'win32' onnon-Windows systems may cause strange behavior.

  • withFileTypes ReturnPathScurryPath objects instead of strings. These are similar to aNodeJSDirent object, but with additional methods andproperties.

    withFileTypes may not be used along withabsolute.

  • signal An AbortSignal which will cancel the Glob walk whentriggered.

  • fs An override object to pass in custom filesystem methods.SeePathScurry docs for what canbe overridden.

  • scurry APathScurry object usedto traverse the file system. If thenocase option is setexplicitly, then any providedscurry object must match thissetting.

  • includeChildMatches boolean, defaulttrue. Do not match anychildren of any matches. For example, the pattern**\/foowould matcha/foo, but nota/foo/b/foo in this mode.

    This is especially useful for cases like "find allnode_modules folders, but not the ones innode_modules".

    In order to support this, theIgnore implementation mustsupport anadd(pattern: string) method. If using the defaultIgnore class, then this is fine, but if this is set tofalse, and a customIgnore is provided that does not haveanadd() method, then it will throw an error.

    Caveat Itonly ignores matches that would be a descendantof a previous match, and only if that descendant is matchedafter the ancestor is encountered. Since the file system walkhappens in indeterminate order, it's possible that a match willalready be added before its ancestor, if multiple or bracedpatterns are used.

    For example:

    constresults=awaitglob([// likely to match first, since it's just a stat'a/b/c/d/e/f',// this pattern is more complicated! It must to various readdir()// calls and test the results against a regular expression, and that// is certainly going to take a little bit longer.//// So, later on, it encounters a match at 'a/b/c/d/e', but it's too// late to ignore a/b/c/d/e/f, because it's already been emitted.'a/[bdf]/?/[a-z]/*',],{includeChildMatches:false},)

    It's best to only set this tofalse if you can be reasonablysure that no components of the pattern will potentially matchone another's file system descendants, or if the occasionalincluded child entry will not cause problems.

Glob Primer

Much more information about glob pattern expansion can be foundby runningman bash and searching forPattern Matching.

"Globs" are the patterns you type when you do stuff likels *.js on the command line, or putbuild/* in a.gitignorefile.

Before parsing the path part patterns, braced sections areexpanded into a set. Braced sections start with{ and end with}, with 2 or more comma-delimited sections within. Bracedsections may contain slash characters, soa{/b/c,bcd} wouldexpand intoa/b/c andabcd.

The following characters have special magic meaning when used ina path portion. With the exception of**, none of these matchpath separators (ie,/ on all platforms, and\ on Windows).

  • * Matches 0 or more characters in a single path portion.When alone in a path portion, it must match at least 1character. Ifdot:true is not specified, then* will notmatch against a. character at the start of a path portion.
  • ? Matches 1 character. Ifdot:true is not specified, then? will not match against a. character at the start of apath portion.
  • [...] Matches a range of characters, similar to a RegExprange. If the first character of the range is! or^ thenit matches any character not in the range. If the firstcharacter is], then it will be considered the same as\],rather than the end of the character class.
  • !(pattern|pattern|pattern) Matches anything that does notmatch any of the patterns provided. Maynot contain/characters. Similar to*, if alone in a path portion, thenthe path portion must have at least one character.
  • ?(pattern|pattern|pattern) Matches zero or one occurrence ofthe patterns provided. Maynot contain/ characters.
  • +(pattern|pattern|pattern) Matches one or more occurrences ofthe patterns provided. Maynot contain/ characters.
  • *(a|b|c) Matches zero or more occurrences of the patternsprovided. Maynot contain/ characters.
  • @(pattern|pat*|pat?erN) Matches exactly one of the patternsprovided. Maynot contain/ characters.
  • ** If a "globstar" is alone in a path portion, then itmatches zero or more directories and subdirectories searchingfor matches. It does not crawl symlinked directories, unless{follow:true} is passed in the options object. A patternlikea/b/** will only matcha/b if it is a directory.Follows 1 symbolic link if not the first item in the pattern,or 0 if it is the first item, unlessfollow:true is set, inwhich case it follows all symbolic links.

[:class:] patterns are supported by this implementation, but[=c=] and[.symbol.] style class patterns are not.

Dots

If a file or directory path portion has a. as the firstcharacter, then it will not match any glob pattern unless thatpattern's corresponding path part also has a. as its firstcharacter.

For example, the patterna/.*/c would match the file ata/.b/c. However the patterna/*/c would not, because* doesnot start with a dot character.

You can make glob treat dots as normal characters by settingdot:true in the options.

Basename Matching

If you setmatchBase:true in the options, and the pattern hasno slashes in it, then it will seek for any file anywhere in thetree with a matching basename. For example,*.js would matchtest/simple/basic.js.

Empty Sets

If no matching files are found, then an empty array is returned.This differs from the shell, where the pattern itself isreturned. For example:

$echo a*s*d*fa*s*d*f

Comparisons to other fnmatch/glob implementations

While strict compliance with the existing standards is aworthwhile goal, some discrepancies exist between node-glob andother implementations, and are intentional.

The double-star character** is supported by default, unlessthenoglobstar flag is set. This is supported in the manner ofbsdglob and bash 5, where** only has special significance ifit is the only thing in a path part. That is,a/**/b will matcha/x/y/b, buta/**b will not.

Note that symlinked directories are not traversed as part of a**, though their contents may match against subsequent portionsof the pattern. This prevents infinite loops and duplicates andthe like. You can force glob to traverse symlinks with** bysetting{follow:true} in the options.

There is no equivalent of thenonull option. A pattern thatdoes not find any matches simply resolves to nothing. (An emptyarray, immediately ended stream, etc.)

If brace expansion is not disabled, then it is performed beforeany other interpretation of the glob pattern. Thus, a patternlike+(a|{b),c)}, which would not be valid in bash or zsh, isexpandedfirst into the set of+(a|b) and+(a|c), andthose patterns are checked for validity. Since those two arevalid, matching proceeds.

The character class patterns[:class:] (posix standard namedclasses) style class patterns are supported and unicode-aware,but[=c=] (locale-specific character collation weight), and[.symbol.] (collating symbol), are not.

Repeated Slashes

Unlike Bash and zsh, repeated/ are always coalesced into asingle path separator.

Comments and Negation

Previously, this module let you mark a pattern as a "comment" ifit started with a# character, or a "negated" pattern if itstarted with a! character.

These options were deprecated in version 5, and removed inversion 6.

To specify things that should not match, use theignore option.

Windows

Please only use forward-slashes in glob expressions.

Though windows uses either/ or\ as its path separator, only/ characters are used by this glob implementation. You must useforward-slashesonly in glob expressions. Back-slashes willalways be interpreted as escape characters, not path separators.

Results from absolute patterns such as/foo/* are mounted ontothe root setting usingpath.join. On windows, this will bydefault result in/foo/* matchingC:\foo\bar.txt.

To automatically coerce all\ characters to/ in patternstrings,thus making it impossible to escape literal globcharacters, you may set thewindowsPathsNoEscape option totrue.

Windows, CWDs, Drive Letters, and UNC Paths

On posix systems, when a pattern starts with/, anycwdoption is ignored, and the traversal starts at/, plus anynon-magic path portions specified in the pattern.

On Windows systems, the behavior is similar, but the concept ofan "absolute path" is somewhat more involved.

UNC Paths

A UNC path may be used as the start of a pattern on Windowsplatforms. For example, a pattern like://?/x:/* will returnall file entries in the root of thex: drive. A pattern like//ComputerName/Share/* will return all files in the associatedshare.

UNC path roots are always compared case insensitively.

Drive Letters

A pattern starting with a drive letter, likec:/*, will searchin that drive, regardless of anycwd option provided.

If the pattern starts with/, and is not a UNC path, and thereis an explicitcwd option set with a drive letter, then thedrive letter in thecwd is used as the root of the directorytraversal.

For example,glob('/tmp', { cwd: 'c:/any/thing' }) will return['c:/tmp'] as the result.

If an explicitcwd option is not provided, and the patternstarts with/, then the traversal will run on the root of thedrive provided as thecwd option. (That is, it is the result ofpath.resolve('/').)

Race Conditions

Glob searching, by its very nature, is susceptible to raceconditions, since it relies on directory walking.

As a result, it is possible that a file that exists when globlooks for it may have been deleted or modified by the time itreturns the result.

By design, this implementation caches all readdir calls that itmakes, in order to cut down on system overhead. However, thisalso makes it even more susceptible to races, especially if thecache object is reused between glob calls.

Users are thus advised not to use a glob result as a guarantee offilesystem state in the face of rapid changes. For the vastmajority of operations, this is never a problem.

See Also:

Glob Logo

Glob's logo was created byTanyaBrassie. Logo files can be foundhere.

The logo is licensed under aCreative CommonsAttribution-ShareAlike 4.0 InternationalLicense.

Contributing

Any change to behavior (including bugfixes) must come with atest.

Patches that fail tests or reduce performance will be rejected.

# to run testsnpmtest# to re-generate test fixturesnpm run test-regen# run the benchmarksnpm run bench# to profile javascriptnpm run prof

Comparison to Other JavaScript Glob Implementations

tl;dr

  • If you want glob matching that is as faithful as possible toBash pattern expansion semantics, and as fast as possiblewithin that constraint,use this module.
  • If you are reasonably sure that the patterns you will encounterare relatively simple, and want the absolutely fastest globmatcher out there,usefast-glob.
  • If you are reasonably sure that the patterns you will encounterare relatively simple, and want the convenience ofautomatically respecting.gitignore files,useglobby.

There are some other glob matcher libraries on npm, but thesethree are (in my opinion, as of 2023) the best.


full explanation

Every library reflects a set of opinions and priorities in thetrade-offs it makes. Other than this library, I can personallyrecommend bothglobby andfast-glob, though they differ in theirbenefits and drawbacks.

Both have very nice APIs and are reasonably fast.

fast-glob is, as far as I am aware, the fastest globimplementation in JavaScript today. However, there are manycases where the choices thatfast-glob makes in pursuit ofspeed mean that its results differ from the results returned byBash and other sh-like shells, which may be surprising.

In my testing,fast-glob is around 10-20% faster than thismodule when walking over 200k files nested 4 directoriesdeep1. However, there are some inconsistencieswith Bash matching behavior that this module does not sufferfrom:

  • ** only matches files, not directories
  • .. path portions are not handled unless they appear at thestart of the pattern
  • ./!(<pattern>) will not match any files thatstart with<pattern>, even if they do not match<pattern>. Forexample,!(9).txt will not match9999.txt.
  • Some brace patterns in the middle of a pattern will result infailing to find certain matches.
  • Extglob patterns are allowed to contain/ characters.

Globby exhibits all of the same pattern semantics as fast-glob,(as it is a wrapper around fast-glob) and is slightly slower thannode-glob (by about 10-20% in the benchmark test set, or in otherwords, anywhere from 20-50% slower than fast-glob). However, itadds some API conveniences that may be worth the costs.

  • Support for.gitignore and other ignore files.
  • Support for negated globs (ie, patterns starting with!rather than using a separateignore option).

The priority of this module is "correctness" in the sense ofperforming a glob pattern expansion as faithfully as possible tothe behavior of Bash and other sh-like shells, with as much speedas possible.

Note that prior versions ofnode-glob arenot on this list.Former versions of this module are far too slow for any caseswhere performance matters at all, and were designed with APIsthat are extremely dated by current JavaScript standards.


[1]: In the cases where this modulereturns results andfast-glob doesn't, it's even faster, ofcourse.

lumpy space princess saying 'oh my GLOB'

Benchmark Results

First number is time, smaller is better.

Second number is the count of results returned.

--- pattern: '**' ---~~ sync ~~node fast-glob sync             0m0.598s  200364node globby sync                0m0.765s  200364node current globSync mjs       0m0.683s  222656node current glob syncStream    0m0.649s  222656~~ async ~~node fast-glob async            0m0.350s  200364node globby async               0m0.509s  200364node current glob async mjs     0m0.463s  222656node current glob stream        0m0.411s  222656--- pattern: '**/..' ---~~ sync ~~node fast-glob sync             0m0.486s  0node globby sync                0m0.769s  200364node current globSync mjs       0m0.564s  2242node current glob syncStream    0m0.583s  2242~~ async ~~node fast-glob async            0m0.283s  0node globby async               0m0.512s  200364node current glob async mjs     0m0.299s  2242node current glob stream        0m0.312s  2242--- pattern: './**/0/**/0/**/0/**/0/**/*.txt' ---~~ sync ~~node fast-glob sync             0m0.490s  10node globby sync                0m0.517s  10node current globSync mjs       0m0.540s  10node current glob syncStream    0m0.550s  10~~ async ~~node fast-glob async            0m0.290s  10node globby async               0m0.296s  10node current glob async mjs     0m0.278s  10node current glob stream        0m0.302s  10--- pattern: './**/[01]/**/[12]/**/[23]/**/[45]/**/*.txt' ---~~ sync ~~node fast-glob sync             0m0.500s  160node globby sync                0m0.528s  160node current globSync mjs       0m0.556s  160node current glob syncStream    0m0.573s  160~~ async ~~node fast-glob async            0m0.283s  160node globby async               0m0.301s  160node current glob async mjs     0m0.306s  160node current glob stream        0m0.322s  160--- pattern: './**/0/**/0/**/*.txt' ---~~ sync ~~node fast-glob sync             0m0.502s  5230node globby sync                0m0.527s  5230node current globSync mjs       0m0.544s  5230node current glob syncStream    0m0.557s  5230~~ async ~~node fast-glob async            0m0.285s  5230node globby async               0m0.305s  5230node current glob async mjs     0m0.304s  5230node current glob stream        0m0.310s  5230--- pattern: '**/*.txt' ---~~ sync ~~node fast-glob sync             0m0.580s  200023node globby sync                0m0.771s  200023node current globSync mjs       0m0.685s  200023node current glob syncStream    0m0.649s  200023~~ async ~~node fast-glob async            0m0.349s  200023node globby async               0m0.509s  200023node current glob async mjs     0m0.427s  200023node current glob stream        0m0.388s  200023--- pattern: '{**/*.txt,**/?/**/*.txt,**/?/**/?/**/*.txt,**/?/**/?/**/?/**/*.txt,**/?/**/?/**/?/**/?/**/*.txt}' ---~~ sync ~~node fast-glob sync             0m0.589s  200023node globby sync                0m0.771s  200023node current globSync mjs       0m0.716s  200023node current glob syncStream    0m0.684s  200023~~ async ~~node fast-glob async            0m0.351s  200023node globby async               0m0.518s  200023node current glob async mjs     0m0.462s  200023node current glob stream        0m0.468s  200023--- pattern: '**/5555/0000/*.txt' ---~~ sync ~~node fast-glob sync             0m0.496s  1000node globby sync                0m0.519s  1000node current globSync mjs       0m0.539s  1000node current glob syncStream    0m0.567s  1000~~ async ~~node fast-glob async            0m0.285s  1000node globby async               0m0.299s  1000node current glob async mjs     0m0.305s  1000node current glob stream        0m0.301s  1000--- pattern: './**/0/**/../[01]/**/0/../**/0/*.txt' ---~~ sync ~~node fast-glob sync             0m0.484s  0node globby sync                0m0.507s  0node current globSync mjs       0m0.577s  4880node current glob syncStream    0m0.586s  4880~~ async ~~node fast-glob async            0m0.280s  0node globby async               0m0.298s  0node current glob async mjs     0m0.327s  4880node current glob stream        0m0.324s  4880--- pattern: '**/????/????/????/????/*.txt' ---~~ sync ~~node fast-glob sync             0m0.547s  100000node globby sync                0m0.673s  100000node current globSync mjs       0m0.626s  100000node current glob syncStream    0m0.618s  100000~~ async ~~node fast-glob async            0m0.315s  100000node globby async               0m0.414s  100000node current glob async mjs     0m0.366s  100000node current glob stream        0m0.345s  100000--- pattern: './{**/?{/**/?{/**/?{/**/?,,,,},,,,},,,,},,,}/**/*.txt' ---~~ sync ~~node fast-glob sync             0m0.588s  100000node globby sync                0m0.670s  100000node current globSync mjs       0m0.717s  200023node current glob syncStream    0m0.687s  200023~~ async ~~node fast-glob async            0m0.343s  100000node globby async               0m0.418s  100000node current glob async mjs     0m0.519s  200023node current glob stream        0m0.451s  200023--- pattern: '**/!(0|9).txt' ---~~ sync ~~node fast-glob sync             0m0.573s  160023node globby sync                0m0.731s  160023node current globSync mjs       0m0.680s  180023node current glob syncStream    0m0.659s  180023~~ async ~~node fast-glob async            0m0.345s  160023node globby async               0m0.476s  160023node current glob async mjs     0m0.427s  180023node current glob stream        0m0.388s  180023--- pattern: './{*/**/../{*/**/../{*/**/../{*/**/../{*/**,,,,},,,,},,,,},,,,},,,,}/*.txt' ---~~ sync ~~node fast-glob sync             0m0.483s  0node globby sync                0m0.512s  0node current globSync mjs       0m0.811s  200023node current glob syncStream    0m0.773s  200023~~ async ~~node fast-glob async            0m0.280s  0node globby async               0m0.299s  0node current glob async mjs     0m0.617s  200023node current glob stream        0m0.568s  200023--- pattern: './*/**/../*/**/../*/**/../*/**/../*/**/../*/**/../*/**/../*/**/*.txt' ---~~ sync ~~node fast-glob sync             0m0.485s  0node globby sync                0m0.507s  0node current globSync mjs       0m0.759s  200023node current glob syncStream    0m0.740s  200023~~ async ~~node fast-glob async            0m0.281s  0node globby async               0m0.297s  0node current glob async mjs     0m0.544s  200023node current glob stream        0m0.464s  200023--- pattern: './*/**/../*/**/../*/**/../*/**/../*/**/*.txt' ---~~ sync ~~node fast-glob sync             0m0.486s  0node globby sync                0m0.513s  0node current globSync mjs       0m0.734s  200023node current glob syncStream    0m0.696s  200023~~ async ~~node fast-glob async            0m0.286s  0node globby async               0m0.296s  0node current glob async mjs     0m0.506s  200023node current glob stream        0m0.483s  200023--- pattern: './0/**/../1/**/../2/**/../3/**/../4/**/../5/**/../6/**/../7/**/*.txt' ---~~ sync ~~node fast-glob sync             0m0.060s  0node globby sync                0m0.074s  0node current globSync mjs       0m0.067s  0node current glob syncStream    0m0.066s  0~~ async ~~node fast-glob async            0m0.060s  0node globby async               0m0.075s  0node current glob async mjs     0m0.066s  0node current glob stream        0m0.067s  0--- pattern: './**/?/**/?/**/?/**/?/**/*.txt' ---~~ sync ~~node fast-glob sync             0m0.568s  100000node globby sync                0m0.651s  100000node current globSync mjs       0m0.619s  100000node current glob syncStream    0m0.617s  100000~~ async ~~node fast-glob async            0m0.332s  100000node globby async               0m0.409s  100000node current glob async mjs     0m0.372s  100000node current glob stream        0m0.351s  100000--- pattern: '**/*/**/*/**/*/**/*/**' ---~~ sync ~~node fast-glob sync             0m0.603s  200113node globby sync                0m0.798s  200113node current globSync mjs       0m0.730s  222137node current glob syncStream    0m0.693s  222137~~ async ~~node fast-glob async            0m0.356s  200113node globby async               0m0.525s  200113node current glob async mjs     0m0.508s  222137node current glob stream        0m0.455s  222137--- pattern: './**/*/**/*/**/*/**/*/**/*.txt' ---~~ sync ~~node fast-glob sync             0m0.622s  200000node globby sync                0m0.792s  200000node current globSync mjs       0m0.722s  200000node current glob syncStream    0m0.695s  200000~~ async ~~node fast-glob async            0m0.369s  200000node globby async               0m0.527s  200000node current glob async mjs     0m0.502s  200000node current glob stream        0m0.481s  200000--- pattern: '**/*.txt' ---~~ sync ~~node fast-glob sync             0m0.588s  200023node globby sync                0m0.771s  200023node current globSync mjs       0m0.684s  200023node current glob syncStream    0m0.658s  200023~~ async ~~node fast-glob async            0m0.352s  200023node globby async               0m0.516s  200023node current glob async mjs     0m0.432s  200023node current glob stream        0m0.384s  200023--- pattern: './**/**/**/**/**/**/**/**/*.txt' ---~~ sync ~~node fast-glob sync             0m0.589s  200023node globby sync                0m0.766s  200023node current globSync mjs       0m0.682s  200023node current glob syncStream    0m0.652s  200023~~ async ~~node fast-glob async            0m0.352s  200023node globby async               0m0.523s  200023node current glob async mjs     0m0.436s  200023node current glob stream        0m0.380s  200023--- pattern: '**/*/*.txt' ---~~ sync ~~node fast-glob sync             0m0.592s  200023node globby sync                0m0.776s  200023node current globSync mjs       0m0.691s  200023node current glob syncStream    0m0.659s  200023~~ async ~~node fast-glob async            0m0.357s  200023node globby async               0m0.513s  200023node current glob async mjs     0m0.471s  200023node current glob stream        0m0.424s  200023--- pattern: '**/*/**/*.txt' ---~~ sync ~~node fast-glob sync             0m0.585s  200023node globby sync                0m0.766s  200023node current globSync mjs       0m0.694s  200023node current glob syncStream    0m0.664s  200023~~ async ~~node fast-glob async            0m0.350s  200023node globby async               0m0.514s  200023node current glob async mjs     0m0.472s  200023node current glob stream        0m0.424s  200023--- pattern: '**/[0-9]/**/*.txt' ---~~ sync ~~node fast-glob sync             0m0.544s  100000node globby sync                0m0.636s  100000node current globSync mjs       0m0.626s  100000node current glob syncStream    0m0.621s  100000~~ async ~~node fast-glob async            0m0.322s  100000node globby async               0m0.404s  100000node current glob async mjs     0m0.360s  100000node current glob stream        0m0.352s  100000

About

glob functionality for node.js

Resources

License

Contributing

Stars

Watchers

Forks

Sponsor this project

 

Packages

No packages published

[8]ページ先頭

©2009-2025 Movatter.jp