Some time ago when I used workbox and did precache, the matching Pattern was based on the Glob Pattern Pattern, so I looked at the relevant documents.

Node-glob: github.com/isaacs/node…


Glob

Like in the shell, files are matched with * and other matching patterns.

Glob is implemented in Javascript using the minimatch library for matching.

use

Install using NPM

npm i glob
Copy the code
var glob = require("glob")

/ / options are optional
glob("**/*.js", options, function (er, files) {
  // files is an array of matched files
  // If 'nonull' in 'options' is true, if not found, files returns ["**/*.js"]
  // 'er' is an error object or null
})
Copy the code

Introduction to Glob

“Glob” is a pattern similar to typing ls *.js on the command line or writing build/* in a.gitignore file.

When parsing the path pattern, braces are separated by commas, and the delimiter can contain /, so a{/b/c, BCD} is expanded to a/b/c and abcd.

The following characters have some special functions when used to match paths:

  • *: Matches 0 or more characters in a single path.
  • ?: Matches a string.
  • [...].: Matches a string in a specified range, similar to a regular expression[]. if[]The first string in is!or^Matches any string that is not in scope.
  • ! (pattern|pattern|pattern): Matches and provides content that does not match in the pattern.
  • ? (pattern|pattern|pattern): Matches 0 or 1 times in the provided pattern.
  • +(pattern|pattern|pattern): Matches one or more of the provided patterns.
  • *(a|b|c): Matches 0 or more times in the provided pattern.
  • @(pattern|pat*|pat? erN)Matches an exact match in the supplied pattern.
  • **And:*Similarly, zero or more of the paths can be matched, and**It can match the current directory and subdirectories. But you can’t grab the directory of the symbolic link.

.point

If the file or directory part matches to. Unless the matching path also starts with. Start, otherwise no pattern will match.

For example, the a/.*/c mode matches a/.b/c. However, the A /*/ C mode does not match because * is not. In the first place.

You can set option dot:true to Glob. As a normal string.

The Basename of the match

If you set matchBase:true in option, when there is no/in the mode, it will match in any directory. For example, *.js will match test/simple/basic.js.

An empty set

If no file is matched, it returns an empty array []. It differs from a shell, which returns itself in case of no match. Such as:

$ echo a*s*d*f
a*s*d*f
Copy the code

You can get the same effect as bash shell by setting optionNonull :true.

glob.hasMagic(pattern, [options])

Return true if there are any special strings in pattern, false otherwise.

Note: Options affect results. If the Settings in the options noext: true, so + (a | b) will not be seen as magic mode. If the pattern supports {} expressions, then it is Magic, such as a/{b/c,x/y}. Unless option sets nobrace:true.

glob(pattern, [options], cb)

  • pattern {String}: Matching mode.
  • options {Object}
  • cb {Function}
    • err {Error | null}
    • matches {Array<String>}: Array of file names after matching patterns.

Perform an asynchronous global search.

glob.sync(pattern, [options])

  • pattern {String}: Matching mode.
  • options {Object}
  • return: {Array<String>}: Indicates the file name in matching mode.

Perform an asynchronous global search.

Class: glob.Glob

Create a glob object by instantiating glob.Glob.

var Glob = require("glob").Glob
var mg = new Glob(pattern, options, cb)
Copy the code

It’s an EventEmitter. It immediately traverses the directory for a match.

new glob.Glob(pattern, [options], [cb])

  • pattern {String}: Matching mode.
  • options {Object}
  • cb {Function}: Successful or failed return.
    • err {Error | null}
    • matches {Array<String>}: Array of matched filenames.

Note that if option sets the sync flag, the result of the match can be obtained by g.ound.

attribute

  • minimatch: used by globminimatchObject.
  • options: The option object passed in.
  • aborted: Boolean value in the callabort()Is set totrue. inabort()After the global search is no longer possible, but can be resetstatCacheTo avoid repeated system calls.
  • cache: Object, which may have the following values:
    • false– The path does not exist.
    • true– The path exists.
    • 'FILE'– A path exists, but it is not a directory.
    • 'DIR'– The path exists and is a directory.
    • [file, entries, ...]– Path exists, result is array, similar tofs.readdirResults.
  • statCache:fs.statResult caching to avoid computing the same path multiple times.
  • symlinks: Records which paths are symbolic links, and**Pattern correlation.
  • realpathCachePassed:fs.realpathTo avoid unnecessary system calls. Stored on instance objects of Glob for reuse.

The event

  • end: Receives the matching result after the match is complete. whennonullSet to include the original pattern string in the returned array if no matches are found. By default, matches are sorted unless setnosort.
  • match: Triggers each time a match is found, and the result contains matching information. It does not delete the real path of duplicates and parses.
  • error: Triggered when an unexpected error occurs. If setoptions.strict, then anyfsError is triggered.
  • abort:abort()Triggered when called.

methods

  • pause: Temporarily suspend the search.
  • resume: Resumes the search.
  • abort: Terminates the search.

options

All Minimatch options can be passed to Glob to change the matching pattern, and some glob-specific features have been added.

All options default to false unless otherwise specified.

All options are also added to the Glob object.

If you are running multiple glob operations, you can pass options on glob objects to later operations to facilitate certain stat and readdir calls. Parallel glob operations can be accelerated by sharing symlinks statCache realpathCache Cache option.

  • cwd: Current directory to search. The defaultprocess.cwd().
  • rootTo:/The starting mount position. The default ispath.resolve(options.cwd, "/")(Unix systems/Some other Windows systems areC:\).
  • dot: in normal mode and**Include in mode.. Note that points defined in the pattern string will always match.File match.
  • nomount: Indicates the default matching mode/The initial one goes to the mount point of the root directory to return a valid file path. Set up thedebugFlag to turn off this behavior.
  • mark: Added in the directory match/. Note that this requires extrastatThe call.
  • nosort: Results are not sorted.
  • statSet:trueStat all results. It can degrade performance and is completely unnecessary unlessreaddirAn unreliable sign that a file exists.
  • silent: Encountered an exception error while reading the directorystderrPrint alarm information. Set the optionsilentTo disable warning messages.
  • strict: Attempts to read directories and encounters an exception error. The search continues for other matches. Set up thestrictWhen these conditions occur, an error is raised.
  • cacheYou can look the samecacheProperties. The cache object generated before passing in saves somefsThe call.
  • statCache: Cache file system information results to prevent unnecessarystatThe call. You usually don’t need to set it, but if you know that the file system won’t change during the call, you canstatCacheFrom aglob()In the options object passed to the other.
  • symlinksA cache of symbolic links is known. In parsing**When a match is made, you can pass in the symlink object you created last time to save itstatThe call.
  • syncDiscard: useglob.sync(pattern, opts)Alternative.
  • nounique: In some cases,{}Pattern causes the same file to appear more than once in the results. By default, it prevents duplicate values from appearing in the results. Setting this property turns this behavior off.
  • nonull: sets not to return an empty array, but an array containing the schema itself. This is aglob(3)The default value in.
  • debug: It will be turned onminimatchandglobEnable logging.
  • nobrace: Do not open the braces, as in{a,b}and{1.. 3}.
  • noglobstar: Indicates that multiple file names do not match**(That is, it will be replaced by normal*).
  • noext: does not match+(a|b)“Extglob” mode.
  • nocase: case insensitive matching. Note: in some case insensitive systemsno-magicPatterns are matched by default,statandreadirWill not raise an error.
  • matchBase: If the schema does not contain/String, the execution is based only on the Basename match. That is to say,*.jsWill be seen as**/*.js, will match all js in all directories.
  • nodir: Matches only files, not directories. Note: matches only directories, just at the end of the pattern/)
  • ignore: Adds an array of patterns or glob patterns to exclude matches. Pay attention to,ignoreAlways in modedot:trueOther Settings are invalid.
  • follow:**In mode, access the symbolic link directory. Note that this can lead to a lot of repeated references when circular links occur.
  • realpath: set totrueIs called in all resultsfs.realpath. Returns the full absolute path to the result of the match under a symbolic link that cannot be resolved. (Although it is usually a broken symbolic link)
  • absolute: Set to true, the absolute path will be received in the matching result. withrealpathDifferent, it also affectsmatchThe return value in the event.

Blog name: Wang Leping blog

CSDN blogs at blog.csdn.net/lecepin


Creative Commons Attribution – Non-commercial Use – No Deductive 4.0 International License