You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

375 lines
15 KiB

4 years ago
  1. # Glob
  2. Match files using the patterns the shell uses, like stars and stuff.
  3. [![Build Status](https://travis-ci.org/isaacs/node-glob.svg?branch=master)](https://travis-ci.org/isaacs/node-glob/) [![Build Status](https://ci.appveyor.com/api/projects/status/kd7f3yftf7unxlsx?svg=true)](https://ci.appveyor.com/project/isaacs/node-glob) [![Coverage Status](https://coveralls.io/repos/isaacs/node-glob/badge.svg?branch=master&service=github)](https://coveralls.io/github/isaacs/node-glob?branch=master)
  4. This is a glob implementation in JavaScript. It uses the `minimatch`
  5. library to do its matching.
  6. ![](logo/glob.png)
  7. ## Usage
  8. Install with npm
  9. ```
  10. npm i glob
  11. ```
  12. ```javascript
  13. var glob = require("glob")
  14. // options is optional
  15. glob("**/*.js", options, function (er, files) {
  16. // files is an array of filenames.
  17. // If the `nonull` option is set, and nothing
  18. // was found, then files is ["**/*.js"]
  19. // er is an error object or null.
  20. })
  21. ```
  22. ## Glob Primer
  23. "Globs" are the patterns you type when you do stuff like `ls *.js` on
  24. the command line, or put `build/*` in a `.gitignore` file.
  25. Before parsing the path part patterns, braced sections are expanded
  26. into a set. Braced sections start with `{` and end with `}`, with any
  27. number of comma-delimited sections within. Braced sections may contain
  28. slash characters, so `a{/b/c,bcd}` would expand into `a/b/c` and `abcd`.
  29. The following characters have special magic meaning when used in a
  30. path portion:
  31. * `*` Matches 0 or more characters in a single path portion
  32. * `?` Matches 1 character
  33. * `[...]` Matches a range of characters, similar to a RegExp range.
  34. If the first character of the range is `!` or `^` then it matches
  35. any character not in the range.
  36. * `!(pattern|pattern|pattern)` Matches anything that does not match
  37. any of the patterns provided.
  38. * `?(pattern|pattern|pattern)` Matches zero or one occurrence of the
  39. patterns provided.
  40. * `+(pattern|pattern|pattern)` Matches one or more occurrences of the
  41. patterns provided.
  42. * `*(a|b|c)` Matches zero or more occurrences of the patterns provided
  43. * `@(pattern|pat*|pat?erN)` Matches exactly one of the patterns
  44. provided
  45. * `**` If a "globstar" is alone in a path portion, then it matches
  46. zero or more directories and subdirectories searching for matches.
  47. It does not crawl symlinked directories.
  48. ### Dots
  49. If a file or directory path portion has a `.` as the first character,
  50. then it will not match any glob pattern unless that pattern's
  51. corresponding path part also has a `.` as its first character.
  52. For example, the pattern `a/.*/c` would match the file at `a/.b/c`.
  53. However the pattern `a/*/c` would not, because `*` does not start with
  54. a dot character.
  55. You can make glob treat dots as normal characters by setting
  56. `dot:true` in the options.
  57. ### Basename Matching
  58. If you set `matchBase:true` in the options, and the pattern has no
  59. slashes in it, then it will seek for any file anywhere in the tree
  60. with a matching basename. For example, `*.js` would match
  61. `test/simple/basic.js`.
  62. ### Empty Sets
  63. If no matching files are found, then an empty array is returned. This
  64. differs from the shell, where the pattern itself is returned. For
  65. example:
  66. $ echo a*s*d*f
  67. a*s*d*f
  68. To get the bash-style behavior, set the `nonull:true` in the options.
  69. ### See Also:
  70. * `man sh`
  71. * `man bash` (Search for "Pattern Matching")
  72. * `man 3 fnmatch`
  73. * `man 5 gitignore`
  74. * [minimatch documentation](https://github.com/isaacs/minimatch)
  75. ## glob.hasMagic(pattern, [options])
  76. Returns `true` if there are any special characters in the pattern, and
  77. `false` otherwise.
  78. Note that the options affect the results. If `noext:true` is set in
  79. the options object, then `+(a|b)` will not be considered a magic
  80. pattern. If the pattern has a brace expansion, like `a/{b/c,x/y}`
  81. then that is considered magical, unless `nobrace:true` is set in the
  82. options.
  83. ## glob(pattern, [options], cb)
  84. * `pattern` `{String}` Pattern to be matched
  85. * `options` `{Object}`
  86. * `cb` `{Function}`
  87. * `err` `{Error | null}`
  88. * `matches` `{Array<String>}` filenames found matching the pattern
  89. Perform an asynchronous glob search.
  90. ## glob.sync(pattern, [options])
  91. * `pattern` `{String}` Pattern to be matched
  92. * `options` `{Object}`
  93. * return: `{Array<String>}` filenames found matching the pattern
  94. Perform a synchronous glob search.
  95. ## Class: glob.Glob
  96. Create a Glob object by instantiating the `glob.Glob` class.
  97. ```javascript
  98. var Glob = require("glob").Glob
  99. var mg = new Glob(pattern, options, cb)
  100. ```
  101. It's an EventEmitter, and starts walking the filesystem to find matches
  102. immediately.
  103. ### new glob.Glob(pattern, [options], [cb])
  104. * `pattern` `{String}` pattern to search for
  105. * `options` `{Object}`
  106. * `cb` `{Function}` Called when an error occurs, or matches are found
  107. * `err` `{Error | null}`
  108. * `matches` `{Array<String>}` filenames found matching the pattern
  109. Note that if the `sync` flag is set in the options, then matches will
  110. be immediately available on the `g.found` member.
  111. ### Properties
  112. * `minimatch` The minimatch object that the glob uses.
  113. * `options` The options object passed in.
  114. * `aborted` Boolean which is set to true when calling `abort()`. There
  115. is no way at this time to continue a glob search after aborting, but
  116. you can re-use the statCache to avoid having to duplicate syscalls.
  117. * `cache` Convenience object. Each field has the following possible
  118. values:
  119. * `false` - Path does not exist
  120. * `true` - Path exists
  121. * `'FILE'` - Path exists, and is not a directory
  122. * `'DIR'` - Path exists, and is a directory
  123. * `[file, entries, ...]` - Path exists, is a directory, and the
  124. array value is the results of `fs.readdir`
  125. * `statCache` Cache of `fs.stat` results, to prevent statting the same
  126. path multiple times.
  127. * `symlinks` A record of which paths are symbolic links, which is
  128. relevant in resolving `**` patterns.
  129. * `realpathCache` An optional object which is passed to `fs.realpath`
  130. to minimize unnecessary syscalls. It is stored on the instantiated
  131. Glob object, and may be re-used.
  132. ### Events
  133. * `end` When the matching is finished, this is emitted with all the
  134. matches found. If the `nonull` option is set, and no match was found,
  135. then the `matches` list contains the original pattern. The matches
  136. are sorted, unless the `nosort` flag is set.
  137. * `match` Every time a match is found, this is emitted with the specific
  138. thing that matched. It is not deduplicated or resolved to a realpath.
  139. * `error` Emitted when an unexpected error is encountered, or whenever
  140. any fs error occurs if `options.strict` is set.
  141. * `abort` When `abort()` is called, this event is raised.
  142. ### Methods
  143. * `pause` Temporarily stop the search
  144. * `resume` Resume the search
  145. * `abort` Stop the search forever
  146. ### Options
  147. All the options that can be passed to Minimatch can also be passed to
  148. Glob to change pattern matching behavior. Also, some have been added,
  149. or have glob-specific ramifications.
  150. All options are false by default, unless otherwise noted.
  151. All options are added to the Glob object, as well.
  152. If you are running many `glob` operations, you can pass a Glob object
  153. as the `options` argument to a subsequent operation to shortcut some
  154. `stat` and `readdir` calls. At the very least, you may pass in shared
  155. `symlinks`, `statCache`, `realpathCache`, and `cache` options, so that
  156. parallel glob operations will be sped up by sharing information about
  157. the filesystem.
  158. * `cwd` The current working directory in which to search. Defaults
  159. to `process.cwd()`.
  160. * `root` The place where patterns starting with `/` will be mounted
  161. onto. Defaults to `path.resolve(options.cwd, "/")` (`/` on Unix
  162. systems, and `C:\` or some such on Windows.)
  163. * `dot` Include `.dot` files in normal matches and `globstar` matches.
  164. Note that an explicit dot in a portion of the pattern will always
  165. match dot files.
  166. * `nomount` By default, a pattern starting with a forward-slash will be
  167. "mounted" onto the root setting, so that a valid filesystem path is
  168. returned. Set this flag to disable that behavior.
  169. * `mark` Add a `/` character to directory matches. Note that this
  170. requires additional stat calls.
  171. * `nosort` Don't sort the results.
  172. * `stat` Set to true to stat *all* results. This reduces performance
  173. somewhat, and is completely unnecessary, unless `readdir` is presumed
  174. to be an untrustworthy indicator of file existence.
  175. * `silent` When an unusual error is encountered when attempting to
  176. read a directory, a warning will be printed to stderr. Set the
  177. `silent` option to true to suppress these warnings.
  178. * `strict` When an unusual error is encountered when attempting to
  179. read a directory, the process will just continue on in search of
  180. other matches. Set the `strict` option to raise an error in these
  181. cases.
  182. * `cache` See `cache` property above. Pass in a previously generated
  183. cache object to save some fs calls.
  184. * `statCache` A cache of results of filesystem information, to prevent
  185. unnecessary stat calls. While it should not normally be necessary
  186. to set this, you may pass the statCache from one glob() call to the
  187. options object of another, if you know that the filesystem will not
  188. change between calls. (See "Race Conditions" below.)
  189. * `symlinks` A cache of known symbolic links. You may pass in a
  190. previously generated `symlinks` object to save `lstat` calls when
  191. resolving `**` matches.
  192. * `sync` DEPRECATED: use `glob.sync(pattern, opts)` instead.
  193. * `nounique` In some cases, brace-expanded patterns can result in the
  194. same file showing up multiple times in the result set. By default,
  195. this implementation prevents duplicates in the result set. Set this
  196. flag to disable that behavior.
  197. * `nonull` Set to never return an empty set, instead returning a set
  198. containing the pattern itself. This is the default in glob(3).
  199. * `debug` Set to enable debug logging in minimatch and glob.
  200. * `nobrace` Do not expand `{a,b}` and `{1..3}` brace sets.
  201. * `noglobstar` Do not match `**` against multiple filenames. (Ie,
  202. treat it as a normal `*` instead.)
  203. * `noext` Do not match `+(a|b)` "extglob" patterns.
  204. * `nocase` Perform a case-insensitive match. Note: on
  205. case-insensitive filesystems, non-magic patterns will match by
  206. default, since `stat` and `readdir` will not raise errors.
  207. * `matchBase` Perform a basename-only match if the pattern does not
  208. contain any slash characters. That is, `*.js` would be treated as
  209. equivalent to `**/*.js`, matching all js files in all directories.
  210. * `nodir` Do not match directories, only files. (Note: to match
  211. *only* directories, simply put a `/` at the end of the pattern.)
  212. * `ignore` Add a pattern or an array of glob patterns to exclude matches.
  213. Note: `ignore` patterns are *always* in `dot:true` mode, regardless
  214. of any other settings.
  215. * `follow` Follow symlinked directories when expanding `**` patterns.
  216. Note that this can result in a lot of duplicate references in the
  217. presence of cyclic links.
  218. * `realpath` Set to true to call `fs.realpath` on all of the results.
  219. In the case of a symlink that cannot be resolved, the full absolute
  220. path to the matched entry is returned (though it will usually be a
  221. broken symlink)
  222. * `absolute` Set to true to always receive absolute paths for matched
  223. files. Unlike `realpath`, this also affects the values returned in
  224. the `match` event.
  225. ## Comparisons to other fnmatch/glob implementations
  226. While strict compliance with the existing standards is a worthwhile
  227. goal, some discrepancies exist between node-glob and other
  228. implementations, and are intentional.
  229. The double-star character `**` is supported by default, unless the
  230. `noglobstar` flag is set. This is supported in the manner of bsdglob
  231. and bash 4.3, where `**` only has special significance if it is the only
  232. thing in a path part. That is, `a/**/b` will match `a/x/y/b`, but
  233. `a/**b` will not.
  234. Note that symlinked directories are not crawled as part of a `**`,
  235. though their contents may match against subsequent portions of the
  236. pattern. This prevents infinite loops and duplicates and the like.
  237. If an escaped pattern has no matches, and the `nonull` flag is set,
  238. then glob returns the pattern as-provided, rather than
  239. interpreting the character escapes. For example,
  240. `glob.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than
  241. `"*a?"`. This is akin to setting the `nullglob` option in bash, except
  242. that it does not resolve escaped pattern characters.
  243. If brace expansion is not disabled, then it is performed before any
  244. other interpretation of the glob pattern. Thus, a pattern like
  245. `+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded
  246. **first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are
  247. checked for validity. Since those two are valid, matching proceeds.
  248. ### Comments and Negation
  249. Previously, this module let you mark a pattern as a "comment" if it
  250. started with a `#` character, or a "negated" pattern if it started
  251. with a `!` character.
  252. These options were deprecated in version 5, and removed in version 6.
  253. To specify things that should not match, use the `ignore` option.
  254. ## Windows
  255. **Please only use forward-slashes in glob expressions.**
  256. Though windows uses either `/` or `\` as its path separator, only `/`
  257. characters are used by this glob implementation. You must use
  258. forward-slashes **only** in glob expressions. Back-slashes will always
  259. be interpreted as escape characters, not path separators.
  260. Results from absolute patterns such as `/foo/*` are mounted onto the
  261. root setting using `path.join`. On windows, this will by default result
  262. in `/foo/*` matching `C:\foo\bar.txt`.
  263. ## Race Conditions
  264. Glob searching, by its very nature, is susceptible to race conditions,
  265. since it relies on directory walking and such.
  266. As a result, it is possible that a file that exists when glob looks for
  267. it may have been deleted or modified by the time it returns the result.
  268. As part of its internal implementation, this program caches all stat
  269. and readdir calls that it makes, in order to cut down on system
  270. overhead. However, this also makes it even more susceptible to races,
  271. especially if the cache or statCache objects are reused between glob
  272. calls.
  273. Users are thus advised not to use a glob result as a guarantee of
  274. filesystem state in the face of rapid changes. For the vast majority
  275. of operations, this is never a problem.
  276. ## Glob Logo
  277. Glob's logo was created by [Tanya Brassie](http://tanyabrassie.com/). Logo files can be found [here](https://github.com/isaacs/node-glob/tree/master/logo).
  278. The logo is licensed under a [Creative Commons Attribution-ShareAlike 4.0 International License](https://creativecommons.org/licenses/by-sa/4.0/).
  279. ## Contributing
  280. Any change to behavior (including bugfixes) must come with a test.
  281. Patches that fail tests or reduce performance will be rejected.
  282. ```
  283. # to run tests
  284. npm test
  285. # to re-generate test fixtures
  286. npm run test-regen
  287. # to benchmark against bash/zsh
  288. npm run bench
  289. # to profile javascript
  290. npm run prof
  291. ```
  292. ![](oh-my-glob.gif)