micromatch vs picomatch
Glob Pattern Matching in JavaScript Projects
micromatchpicomatchSimilar Packages:

Glob Pattern Matching in JavaScript Projects

micromatch and picomatch are both high-performance libraries for matching file paths and strings against glob patterns in JavaScript. micromatch is a mature, feature-rich glob matcher often used in build tools and file watchers, providing a high-level API for complex matching scenarios. picomatch is a lighter, faster glob parser and matcher designed for speed and minimal dependencies, frequently used as a core engine within other tools including newer versions of micromatch itself.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
micromatch03,02456.6 kB442 years agoMIT
picomatch01,22291.4 kB382 days agoMIT

Micromatch vs Picomatch: Architecture, API, and Performance Compared

Both micromatch and picomatch solve the same fundamental problem: matching strings (usually file paths) against glob patterns like *.js or src/**/test.ts. However, they sit at different layers of the abstraction stack. micromatch is a high-level utility built for developer ergonomics and complex file matching, while picomatch is a low-level engine optimized for speed and minimal overhead. Let's compare how they handle real-world engineering scenarios.

🎯 Core Philosophy: High-Level Utility vs Low-Level Engine

micromatch focuses on providing a complete API for file matching.

  • It handles edge cases in file paths automatically.
  • It includes features like .not(), .any(), and .isMatch() for complex logic.
  • Historically, it wrapped other engines, but modern versions often use picomatch internally.
// micromatch: High-level API
const mm = require('micromatch');

const files = ['src/a.js', 'src/b.ts', 'test/a.js'];
// Match with negation and complex patterns
const result = mm.match(files, ['*.js', '!test/**']);
// Returns: ['src/a.js']

picomatch focuses on raw matching speed and parsing accuracy.

  • It exports functions like parse(), compile(), and scan() for introspection.
  • It is designed to be embedded in other tools rather than used directly for file system traversal.
  • It returns a matcher function for repeated use, which is faster for large lists.
// picomatch: Low-level engine
const pm = require('picomatch');

const isMatch = pm('*.js', { ignore: 'test/**' });
const files = ['src/a.js', 'src/b.ts', 'test/a.js'];

// Reuse the compiled matcher for performance
const result = files.filter(isMatch);
// Returns: ['src/a.js']

⚑ Performance Strategy: Convenience vs Optimization

micromatch optimizes for developer time and feature completeness.

  • It accepts arrays of patterns and files directly in one call.
  • It handles normalization of paths (Windows vs Unix slashes) internally.
  • Slight overhead exists due to additional safety checks and feature support.
// micromatch: Direct array matching
const mm = require('micromatch');

// One-liner for matching lists
const matches = mm(['foo/bar.js', 'baz/qux.ts'], '**/*.js');
// Handles path separators and options internally

picomatch optimizes for execution speed and memory usage.

  • It encourages compiling patterns once and reusing the matcher function.
  • It avoids path normalization overhead unless explicitly requested.
  • Ideal for hot paths where the same pattern matches thousands of strings.
// picomatch: Compiled matcher reuse
const pm = require('picomatch');

// Compile once
const matcher = pm.compile('**/*.js');

// Execute many times
const matches = ['foo/bar.js', 'baz/qux.ts'].filter(matcher);
// Faster for repeated operations on large datasets

πŸ› οΈ Feature Set: Advanced Globbing vs Core Parsing

micromatch supports advanced glob features and helpers.

  • Includes helpers like makeRe() to convert globs to Regex.
  • Supports .not() to exclude patterns easily without complex logic.
  • Better support for Windows paths and edge cases in file systems.
// micromatch: Advanced helpers
const mm = require('micromatch');

// Exclude patterns easily
const result = mm.not(['a.js', 'b.js', 'c.ts'], '*.ts');
// Returns: ['a.js', 'b.js']

// Convert to Regex
const regex = mm.makeRe('*.js');

picomatch provides deep introspection into the pattern itself.

  • Exposes scan() to analyze pattern properties (is glob? has braces?).
  • Exposes parse() to get the AST of the glob pattern.
  • Less focus on file-system-specific helpers, more on string matching logic.
// picomatch: Pattern introspection
const pm = require('picomatch');

// Scan pattern properties
const scan = pm.scan('**/*.js');
console.log(scan.isGlob); // true

// Parse pattern into AST
const ast = pm.parse('*.js');
// Returns object representing pattern structure

🌐 Environment Support: Node.js vs Universal

micromatch is primarily designed for Node.js environments.

  • Relies on Node-specific path resolution in some edge cases.
  • Commonly used in build tools (Webpack, Gulp, Vite) running on servers.
  • Less suitable for browser bundles due to size and Node dependencies.
// micromatch: Node-centric
const mm = require('micromatch');

// Often used with fs module
const fs = require('fs');
const files = fs.readdirSync('.');
const jsFiles = mm(files, '*.js');

picomatch is designed to be universal (Node and Browser).

  • Has zero dependencies, making it easy to bundle.
  • Works consistently across environments without path normalization assumptions.
  • Preferred for client-side tools or isomorphic libraries.
// picomatch: Universal support
import picomatch from 'picomatch';

// Works in browser bundles without polyfills
const isJS = picomatch('*.js');
console.log(isJS('script.js')); // true

🀝 Similarities: Shared Ground Between Micromatch and Picomatch

While they target different layers, both libraries share core matching logic and standards.

1. πŸ“œ Bash-Style Glob Support

  • Both support standard glob patterns (*, **, ?, []).
  • Both handle brace expansion {a,b} and extglobs +(pattern).
// Both support brace expansion
// micromatch
mm(['a.js', 'b.js'], '{a,b}.js'); // ['a.js', 'b.js']

// picomatch
pm('{a,b}.js')('a.js'); // true

2. 🚫 Negation Support

  • Both allow excluding patterns using !.
  • Logic for handling negation is consistent between the two.
// Both support negation
// micromatch
mm.match(['a.js', 'b.js'], ['*', '!b.js']); // ['a.js']

// picomatch
const isMatch = pm(['*', '!b.js']);
isMatch('a.js'); // true

3. βš™οΈ Configuration Options

  • Both accept options objects to toggle features (dotfiles, case sensitivity).
  • Options like dot, nocase, and ignore behave similarly.
// Both support options
// micromatch
mm.match(['.secret.js'], '*.js', { dot: true });

// picomatch
const isMatch = pm('*.js', { dot: true });
isMatch('.secret.js'); // true

4. βœ… Accuracy and Compliance

  • Both aim for high compliance with bash globbing standards.
  • Edge cases in pattern matching are handled consistently.
// Both handle edge cases similarly
// micromatch
mm.isMatch('foo/bar', 'foo/bar'); // true

// picomatch
pm.isMatch('foo/bar', 'foo/bar'); // true

5. πŸ‘₯ Maintenance and Ecosystem

  • Both are actively maintained by the same core community (Jon Schlinkert).
  • Widely used in the JavaScript ecosystem (linters, bundlers, test runners).
// Both are trusted in major tools
// Used in: ESLint, Jest, Vite, Rollup, etc.
// Implementation details vary, but reliability is high for both

πŸ“Š Summary: Key Similarities

FeatureShared by Micromatch and Picomatch
Pattern SyntaxπŸ“œ Bash-style globs, braces, extglobs
Negation🚫 ! support for exclusion
Optionsβš™οΈ dot, nocase, ignore
Accuracyβœ… High compliance with standards
MaintenanceπŸ‘₯ Active, same core maintainers

πŸ†š Summary: Key Differences

Featuremicromatchpicomatch
AbstractionπŸ› οΈ High-level file matching utilityβš™οΈ Low-level glob engine
API StyleπŸ“¦ match(list, patterns)🧩 matcher = compile(pattern)
Performance🐒 Optimized for featuresπŸš€ Optimized for speed
DependenciesπŸ“¦ Includes picomatch + helpersπŸƒ Zero dependencies
EnvironmentπŸ’» Node.js focused🌐 Universal (Node + Browser)
IntrospectionπŸ” Limited pattern analysisπŸ”¬ Deep AST and scan support

πŸ’‘ The Big Picture

micromatch is like a power drill πŸ§°β€”it comes with all the attachments you need to get the job done quickly. It handles the messy details of file paths, negation, and array matching so you don't have to. Use it when you are building tooling that needs to match files reliably and you value API convenience over raw cycle count.

picomatch is like the motor inside the drill πŸ”‹β€”it's the raw power source. It's smaller, faster, and gives you direct control. Use it when you are building a library where bundle size matters, or when you need to match the same pattern against millions of strings in a hot loop.

Final Thought: In many modern projects, you don't have to choose strictly. micromatch now uses picomatch under the hood. If you need file matching helpers, use micromatch. If you need a lightweight string matcher, use picomatch. Both are industry standards for globbing in JavaScript.

How to Choose: micromatch vs picomatch

  • micromatch:

    Choose micromatch if you need a robust, battle-tested solution for file system operations with advanced features like negation, brace expansion, and extglob support out of the box. It is ideal for build tools, task runners, or any scenario where you need to match large sets of file paths with complex rules and require a stable, high-level API.

  • picomatch:

    Choose picomatch if you prioritize raw speed, smaller bundle size, or need a low-level glob parser for custom implementations. It is suitable for performance-critical paths, browser environments where bundle size matters, or when you want to minimize dependencies while still having accurate bash-style glob matching.

README for micromatch

micromatch NPM version NPM monthly downloads NPM total downloads Tests

Glob matching for javascript/node.js. A replacement and faster alternative to minimatch and multimatch.

Please consider following this project's author, Jon Schlinkert, and consider starring the project to show your :heart: and support.

Table of Contents

Details

Install

Install with npm:

$ npm install --save micromatch

Sponsors

Become a Sponsor to add your logo to this README, or any of my other projects


Quickstart

const micromatch = require('micromatch');
// micromatch(list, patterns[, options]);

The main export takes a list of strings and one or more glob patterns:

console.log(micromatch(['foo', 'bar', 'baz', 'qux'], ['f*', 'b*'])) //=> ['foo', 'bar', 'baz']
console.log(micromatch(['foo', 'bar', 'baz', 'qux'], ['*', '!b*'])) //=> ['foo', 'qux']

Use .isMatch() to for boolean matching:

console.log(micromatch.isMatch('foo', 'f*')) //=> true
console.log(micromatch.isMatch('foo', ['b*', 'f*'])) //=> true

Switching from minimatch and multimatch is easy!


Why use micromatch?

micromatch is a replacement for minimatch and multimatch

  • Supports all of the same matching features as minimatch and multimatch
  • More complete support for the Bash 4.3 specification than minimatch and multimatch. Micromatch passes all of the spec tests from bash, including some that bash still fails.
  • Fast & Performant - Loads in about 5ms and performs fast matches.
  • Glob matching - Using wildcards (* and ?), globstars (**) for nested directories
  • Advanced globbing - Supports extglobs, braces, and POSIX brackets, and support for escaping special characters with \ or quotes.
  • Accurate - Covers more scenarios than minimatch
  • Well tested - More than 5,000 test assertions
  • Windows support - More reliable windows support than minimatch and multimatch.
  • Safe - Micromatch is not subject to DoS with brace patterns like minimatch and multimatch.

Matching features

  • Support for multiple glob patterns (no need for wrappers like multimatch)
  • Wildcards (**, *.js)
  • Negation ('!a/*.js', '*!(b).js')
  • extglobs (+(x|y), !(a|b))
  • POSIX character classes ([[:alpha:][:digit:]])
  • brace expansion (foo/{1..5}.md, bar/{a,b,c}.js)
  • regex character classes (foo-[1-5].js)
  • regex logical "or" (foo/(abc|xyz).js)

You can mix and match these features to create whatever patterns you need!

Switching to micromatch

(There is one notable difference between micromatch and minimatch in regards to how backslashes are handled. See the notes about backslashes for more information.)

From minimatch

Use micromatch.isMatch() instead of minimatch():

console.log(micromatch.isMatch('foo', 'b*')); //=> false

Use micromatch.match() instead of minimatch.match():

console.log(micromatch.match(['foo', 'bar'], 'b*')); //=> 'bar'

From multimatch

Same signature:

console.log(micromatch(['foo', 'bar', 'baz'], ['f*', '*z'])); //=> ['foo', 'baz']

API

Params

  • list {String|Array}: List of strings to match.
  • patterns {String|Array}: One or more glob patterns to use for matching.
  • options {Object}: See available options
  • returns {Array}: Returns an array of matches

Example

const mm = require('micromatch');
// mm(list, patterns[, options]);

console.log(mm(['a.js', 'a.txt'], ['*.js']));
//=> [ 'a.js' ]

.matcher

Returns a matcher function from the given glob pattern and options. The returned function takes a string to match as its only argument and returns true if the string is a match.

Params

  • pattern {String}: Glob pattern
  • options {Object}
  • returns {Function}: Returns a matcher function.

Example

const mm = require('micromatch');
// mm.matcher(pattern[, options]);

const isMatch = mm.matcher('*.!(*a)');
console.log(isMatch('a.a')); //=> false
console.log(isMatch('a.b')); //=> true

.isMatch

Returns true if any of the given glob patterns match the specified string.

Params

  • str {String}: The string to test.
  • patterns {String|Array}: One or more glob patterns to use for matching.
  • [options] {Object}: See available options.
  • returns {Boolean}: Returns true if any patterns match str

Example

const mm = require('micromatch');
// mm.isMatch(string, patterns[, options]);

console.log(mm.isMatch('a.a', ['b.*', '*.a'])); //=> true
console.log(mm.isMatch('a.a', 'b.*')); //=> false

.not

Returns a list of strings that do not match any of the given patterns.

Params

  • list {Array}: Array of strings to match.
  • patterns {String|Array}: One or more glob pattern to use for matching.
  • options {Object}: See available options for changing how matches are performed
  • returns {Array}: Returns an array of strings that do not match the given patterns.

Example

const mm = require('micromatch');
// mm.not(list, patterns[, options]);

console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a'));
//=> ['b.b', 'c.c']

.contains

Returns true if the given string contains the given pattern. Similar to .isMatch but the pattern can match any part of the string.

Params

  • str {String}: The string to match.
  • patterns {String|Array}: Glob pattern to use for matching.
  • options {Object}: See available options for changing how matches are performed
  • returns {Boolean}: Returns true if any of the patterns matches any part of str.

Example

var mm = require('micromatch');
// mm.contains(string, pattern[, options]);

console.log(mm.contains('aa/bb/cc', '*b'));
//=> true
console.log(mm.contains('aa/bb/cc', '*d'));
//=> false

.matchKeys

Filter the keys of the given object with the given glob pattern and options. Does not attempt to match nested keys. If you need this feature, use glob-object instead.

Params

  • object {Object}: The object with keys to filter.
  • patterns {String|Array}: One or more glob patterns to use for matching.
  • options {Object}: See available options for changing how matches are performed
  • returns {Object}: Returns an object with only keys that match the given patterns.

Example

const mm = require('micromatch');
// mm.matchKeys(object, patterns[, options]);

const obj = { aa: 'a', ab: 'b', ac: 'c' };
console.log(mm.matchKeys(obj, '*b'));
//=> { ab: 'b' }

.some

Returns true if some of the strings in the given list match any of the given glob patterns.

Params

  • list {String|Array}: The string or array of strings to test. Returns as soon as the first match is found.
  • patterns {String|Array}: One or more glob patterns to use for matching.
  • options {Object}: See available options for changing how matches are performed
  • returns {Boolean}: Returns true if any patterns matches any of the strings in list

Example

const mm = require('micromatch');
// mm.some(list, patterns[, options]);

console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
// true
console.log(mm.some(['foo.js'], ['*.js', '!foo.js']));
// false

.every

Returns true if every string in the given list matches any of the given glob patterns.

Params

  • list {String|Array}: The string or array of strings to test.
  • patterns {String|Array}: One or more glob patterns to use for matching.
  • options {Object}: See available options for changing how matches are performed
  • returns {Boolean}: Returns true if all patterns matches all of the strings in list

Example

const mm = require('micromatch');
// mm.every(list, patterns[, options]);

console.log(mm.every('foo.js', ['foo.js']));
// true
console.log(mm.every(['foo.js', 'bar.js'], ['*.js']));
// true
console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
// false
console.log(mm.every(['foo.js'], ['*.js', '!foo.js']));
// false

.all

Returns true if all of the given patterns match the specified string.

Params

  • str {String|Array}: The string to test.
  • patterns {String|Array}: One or more glob patterns to use for matching.
  • options {Object}: See available options for changing how matches are performed
  • returns {Boolean}: Returns true if any patterns match str

Example

const mm = require('micromatch');
// mm.all(string, patterns[, options]);

console.log(mm.all('foo.js', ['foo.js']));
// true

console.log(mm.all('foo.js', ['*.js', '!foo.js']));
// false

console.log(mm.all('foo.js', ['*.js', 'foo.js']));
// true

console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js']));
// true

.capture

Returns an array of matches captured by pattern in string, ornull` if the pattern did not match.

Params

  • glob {String}: Glob pattern to use for matching.
  • input {String}: String to match
  • options {Object}: See available options for changing how matches are performed
  • returns {Array|null}: Returns an array of captures if the input matches the glob pattern, otherwise null.

Example

const mm = require('micromatch');
// mm.capture(pattern, string[, options]);

console.log(mm.capture('test/*.js', 'test/foo.js'));
//=> ['foo']
console.log(mm.capture('test/*.js', 'foo/bar.css'));
//=> null

.makeRe

Create a regular expression from the given glob pattern.

Params

  • pattern {String}: A glob pattern to convert to regex.
  • options {Object}
  • returns {RegExp}: Returns a regex created from the given pattern.

Example

const mm = require('micromatch');
// mm.makeRe(pattern[, options]);

console.log(mm.makeRe('*.js'));
//=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/

.scan

Scan a glob pattern to separate the pattern into segments. Used by the split method.

Params

  • pattern {String}
  • options {Object}
  • returns {Object}: Returns an object with

Example

const mm = require('micromatch');
const state = mm.scan(pattern[, options]);

.parse

Parse a glob pattern to create the source string for a regular expression.

Params

  • glob {String}
  • options {Object}
  • returns {Object}: Returns an object with useful properties and output to be used as regex source string.

Example

const mm = require('micromatch');
const state = mm.parse(pattern[, options]);

.braces

Process the given brace pattern.

Params

  • pattern {String}: String with brace pattern to process.
  • options {Object}: Any options to change how expansion is performed. See the braces library for all available options.
  • returns {Array}

Example

const { braces } = require('micromatch');
console.log(braces('foo/{a,b,c}/bar'));
//=> [ 'foo/(a|b|c)/bar' ]

console.log(braces('foo/{a,b,c}/bar', { expand: true }));
//=> [ 'foo/a/bar', 'foo/b/bar', 'foo/c/bar' ]

Options

OptionTypeDefault valueDescription
basenamebooleanfalseIf set, then patterns without slashes will be matched against the basename of the path if it contains slashes. For example, a?b would match the path /xyz/123/acb, but not /xyz/acb/123.
bashbooleanfalseFollow bash matching rules more strictly - disallows backslashes as escape characters, and treats single stars as globstars (**).
capturebooleanundefinedReturn regex matches in supporting methods.
containsbooleanundefinedAllows glob to match any part of the given string(s).
cwdstringprocess.cwd()Current working directory. Used by picomatch.split()
debugbooleanundefinedDebug regular expressions when an error is thrown.
dotbooleanfalseMatch dotfiles. Otherwise dotfiles are ignored unless a . is explicitly defined in the pattern.
expandRangefunctionundefinedCustom function for expanding ranges in brace patterns, such as {a..z}. The function receives the range values as two arguments, and it must return a string to be used in the generated regex. It's recommended that returned strings be wrapped in parentheses. This option is overridden by the expandBrace option.
failglobbooleanfalseSimilar to the failglob behavior in Bash, throws an error when no matches are found. Based on the bash option of the same name.
fastpathsbooleantrueTo speed up processing, full parsing is skipped for a handful common glob patterns. Disable this behavior by setting this option to false.
flagsbooleanundefinedRegex flags to use in the generated regex. If defined, the nocase option will be overridden.
formatfunctionundefinedCustom function for formatting the returned string. This is useful for removing leading slashes, converting Windows paths to Posix paths, etc.
ignorearray|stringundefinedOne or more glob patterns for excluding strings that should not be matched from the result.
keepQuotesbooleanfalseRetain quotes in the generated regex, since quotes may also be used as an alternative to backslashes.
literalBracketsbooleanundefinedWhen true, brackets in the glob pattern will be escaped so that only literal brackets will be matched.
lookbehindsbooleantrueSupport regex positive and negative lookbehinds. Note that you must be using Node 8.1.10 or higher to enable regex lookbehinds.
matchBasebooleanfalseAlias for basename
maxLengthboolean65536Limit the max length of the input string. An error is thrown if the input string is longer than this value.
nobracebooleanfalseDisable brace matching, so that {a,b} and {1..3} would be treated as literal characters.
nobracketbooleanundefinedDisable matching with regex brackets.
nocasebooleanfalsePerform case-insensitive matching. Equivalent to the regex i flag. Note that this option is ignored when the flags option is defined.
nodupesbooleantrueDeprecated, use nounique instead. This option will be removed in a future major release. By default duplicates are removed. Disable uniquification by setting this option to false.
noextbooleanfalseAlias for noextglob
noextglobbooleanfalseDisable support for matching with extglobs (like +(a|b))
noglobstarbooleanfalseDisable support for matching nested directories with globstars (**)
nonegatebooleanfalseDisable support for negating with leading !
noquantifiersbooleanfalseDisable support for regex quantifiers (like a{1,2}) and treat them as brace patterns to be expanded.
onIgnorefunctionundefinedFunction to be called on ignored items.
onMatchfunctionundefinedFunction to be called on matched items.
onResultfunctionundefinedFunction to be called on all items, regardless of whether or not they are matched or ignored.
posixbooleanfalseSupport POSIX character classes ("posix brackets").
posixSlashesbooleanundefinedConvert all slashes in file paths to forward slashes. This does not convert slashes in the glob pattern itself
prependstringundefinedString to prepend to the generated regex used for matching.
regexbooleanfalseUse regular expression rules for + (instead of matching literal +), and for stars that follow closing parentheses or brackets (as in )* and ]*).
strictBracketsbooleanundefinedThrow an error if brackets, braces, or parens are imbalanced.
strictSlashesbooleanundefinedWhen true, picomatch won't match trailing slashes with single stars.
unescapebooleanundefinedRemove preceding backslashes from escaped glob characters before creating the regular expression to perform matches.
unixifybooleanundefinedAlias for posixSlashes, for backwards compatitibility.

Options Examples

options.basename

Allow glob patterns without slashes to match a file path based on its basename. Same behavior as minimatch option matchBase.

Type: Boolean

Default: false

Example

micromatch(['a/b.js', 'a/c.md'], '*.js');
//=> []

micromatch(['a/b.js', 'a/c.md'], '*.js', { basename: true });
//=> ['a/b.js']

options.bash

Enabled by default, this option enforces bash-like behavior with stars immediately following a bracket expression. Bash bracket expressions are similar to regex character classes, but unlike regex, a star following a bracket expression does not repeat the bracketed characters. Instead, the star is treated the same as any other star.

Type: Boolean

Default: true

Example

const files = ['abc', 'ajz'];
console.log(micromatch(files, '[a-c]*'));
//=> ['abc', 'ajz']

console.log(micromatch(files, '[a-c]*', { bash: false }));

options.expandRange

Type: function

Default: undefined

Custom function for expanding ranges in brace patterns. The fill-range library is ideal for this purpose, or you can use custom code to do whatever you need.

Example

The following example shows how to create a glob that matches a numeric folder name between 01 and 25, with leading zeros.

const fill = require('fill-range');
const regex = micromatch.makeRe('foo/{01..25}/bar', {
  expandRange(a, b) {
    return `(${fill(a, b, { toRegex: true })})`;
  }
});

console.log(regex)
//=> /^(?:foo\/((?:0[1-9]|1[0-9]|2[0-5]))\/bar)$/

console.log(regex.test('foo/00/bar')) // false
console.log(regex.test('foo/01/bar')) // true
console.log(regex.test('foo/10/bar')) // true
console.log(regex.test('foo/22/bar')) // true
console.log(regex.test('foo/25/bar')) // true
console.log(regex.test('foo/26/bar')) // false

options.format

Type: function

Default: undefined

Custom function for formatting strings before they're matched.

Example

// strip leading './' from strings
const format = str => str.replace(/^\.\//, '');
const isMatch = picomatch('foo/*.js', { format });
console.log(isMatch('./foo/bar.js')) //=> true

options.ignore

String or array of glob patterns to match files to ignore.

Type: String|Array

Default: undefined

const isMatch = micromatch.matcher('*', { ignore: 'f*' });
console.log(isMatch('foo')) //=> false
console.log(isMatch('bar')) //=> true
console.log(isMatch('baz')) //=> true

options.matchBase

Alias for options.basename.

options.noextglob

Disable extglob support, so that extglobs are regarded as literal characters.

Type: Boolean

Default: undefined

Examples

console.log(micromatch(['a/z', 'a/b', 'a/!(z)'], 'a/!(z)'));
//=> ['a/b', 'a/!(z)']

console.log(micromatch(['a/z', 'a/b', 'a/!(z)'], 'a/!(z)', { noextglob: true }));
//=> ['a/!(z)'] (matches only as literal characters)

options.nonegate

Disallow negation (!) patterns, and treat leading ! as a literal character to match.

Type: Boolean

Default: undefined

options.noglobstar

Disable matching with globstars (**).

Type: Boolean

Default: undefined

micromatch(['a/b', 'a/b/c', 'a/b/c/d'], 'a/**');
//=> ['a/b', 'a/b/c', 'a/b/c/d']

micromatch(['a/b', 'a/b/c', 'a/b/c/d'], 'a/**', {noglobstar: true});
//=> ['a/b']

options.nonull

Alias for options.nullglob.

options.nullglob

If true, when no matches are found the actual (arrayified) glob pattern is returned instead of an empty array. Same behavior as minimatch option nonull.

Type: Boolean

Default: undefined

options.onIgnore

const onIgnore = ({ glob, regex, input, output }) => {
  console.log({ glob, regex, input, output });
  // { glob: '*', regex: /^(?:(?!\.)(?=.)[^\/]*?\/?)$/, input: 'foo', output: 'foo' }
};

const isMatch = micromatch.matcher('*', { onIgnore, ignore: 'f*' });
isMatch('foo');
isMatch('bar');
isMatch('baz');

options.onMatch

const onMatch = ({ glob, regex, input, output }) => {
  console.log({ input, output });
  // { input: 'some\\path', output: 'some/path' }
  // { input: 'some\\path', output: 'some/path' }
  // { input: 'some\\path', output: 'some/path' }
};

const isMatch = micromatch.matcher('**', { onMatch, posixSlashes: true });
isMatch('some\\path');
isMatch('some\\path');
isMatch('some\\path');

options.onResult

const onResult = ({ glob, regex, input, output }) => {
  console.log({ glob, regex, input, output });
};

const isMatch = micromatch('*', { onResult, ignore: 'f*' });
isMatch('foo');
isMatch('bar');
isMatch('baz');

options.posixSlashes

Convert path separators on returned files to posix/unix-style forward slashes. Aliased as unixify for backwards compatibility.

Type: Boolean

Default: true on windows, false everywhere else.

Example

console.log(micromatch.match(['a\\b\\c'], 'a/**'));
//=> ['a/b/c']

console.log(micromatch.match(['a\\b\\c'], { posixSlashes: false }));
//=> ['a\\b\\c']

options.unescape

Remove backslashes from escaped glob characters before creating the regular expression to perform matches.

Type: Boolean

Default: undefined

Example

In this example we want to match a literal *:

console.log(micromatch.match(['abc', 'a\\*c'], 'a\\*c'));
//=> ['a\\*c']

console.log(micromatch.match(['abc', 'a\\*c'], 'a\\*c', { unescape: true }));
//=> ['a*c']


Extended globbing

Micromatch supports the following extended globbing features.

Extglobs

Extended globbing, as described by the bash man page:

patternregex equivalentdescription
?(pattern)(pattern)?Matches zero or one occurrence of the given patterns
*(pattern)(pattern)*Matches zero or more occurrences of the given patterns
+(pattern)(pattern)+Matches one or more occurrences of the given patterns
@(pattern)(pattern) *Matches one of the given patterns
!(pattern)N/A (equivalent regex is much more complicated)Matches anything except one of the given patterns

* Note that @ isn't a regex character.

Braces

Brace patterns can be used to match specific ranges or sets of characters.

Example

The pattern {f,b}*/{1..3}/{b,q}* would match any of following strings:

foo/1/bar
foo/2/bar
foo/3/bar
baz/1/qux
baz/2/qux
baz/3/qux

Visit braces to see the full range of features and options related to brace expansion, or to create brace matching or expansion related issues.

Regex character classes

Given the list: ['a.js', 'b.js', 'c.js', 'd.js', 'E.js']:

  • [ac].js: matches both a and c, returning ['a.js', 'c.js']
  • [b-d].js: matches from b to d, returning ['b.js', 'c.js', 'd.js']
  • a/[A-Z].js: matches and uppercase letter, returning ['a/E.md']

Learn about regex character classes.

Regex groups

Given ['a.js', 'b.js', 'c.js', 'd.js', 'E.js']:

  • (a|c).js: would match either a or c, returning ['a.js', 'c.js']
  • (b|d).js: would match either b or d, returning ['b.js', 'd.js']
  • (b|[A-Z]).js: would match either b or an uppercase letter, returning ['b.js', 'E.js']

As with regex, parens can be nested, so patterns like ((a|b)|c)/b will work. Although brace expansion might be friendlier to use, depending on preference.

POSIX bracket expressions

POSIX brackets are intended to be more user-friendly than regex character classes. This of course is in the eye of the beholder.

Example

console.log(micromatch.isMatch('a1', '[[:alpha:][:digit:]]')) //=> true
console.log(micromatch.isMatch('a1', '[[:alpha:][:alpha:]]')) //=> false

Notes

Bash 4.3 parity

Whenever possible matching behavior is based on behavior Bash 4.3, which is mostly consistent with minimatch.

However, it's suprising how many edge cases and rabbit holes there are with glob matching, and since there is no real glob specification, and micromatch is more accurate than both Bash and minimatch, there are cases where best-guesses were made for behavior. In a few cases where Bash had no answers, we used wildmatch (used by git) as a fallback.

Backslashes

There is an important, notable difference between minimatch and micromatch in regards to how backslashes are handled in glob patterns.

  • Micromatch exclusively and explicitly reserves backslashes for escaping characters in a glob pattern, even on windows, which is consistent with bash behavior. More importantly, unescaping globs can result in unsafe regular expressions.
  • Minimatch converts all backslashes to forward slashes, which means you can't use backslashes to escape any characters in your glob patterns.

We made this decision for micromatch for a couple of reasons:

  • Consistency with bash conventions.
  • Glob patterns are not filepaths. They are a type of regular language that is converted to a JavaScript regular expression. Thus, when forward slashes are defined in a glob pattern, the resulting regular expression will match windows or POSIX path separators just fine.

A note about joining paths to globs

Note that when you pass something like path.join('foo', '*') to micromatch, you are creating a filepath and expecting it to still work as a glob pattern. This causes problems on windows, since the path.sep is \\.

In other words, since \\ is reserved as an escape character in globs, on windows path.join('foo', '*') would result in foo\\*, which tells micromatch to match * as a literal character. This is the same behavior as bash.

To solve this, you might be inspired to do something like 'foo\\*'.replace(/\\/g, '/'), but this causes another, potentially much more serious, problem.

Benchmarks

Running benchmarks

Install dependencies for running benchmarks:

$ cd bench && npm install

Run the benchmarks:

$ npm run bench

Latest results

As of August 23, 2024 (longer bars are better):

# .makeRe star
  micromatch x 2,232,802 ops/sec Β±2.34% (89 runs sampled))
  minimatch x 781,018 ops/sec Β±6.74% (92 runs sampled))

# .makeRe star; dot=true
  micromatch x 1,863,453 ops/sec Β±0.74% (93 runs sampled)
  minimatch x 723,105 ops/sec Β±0.75% (93 runs sampled)

# .makeRe globstar
  micromatch x 1,624,179 ops/sec Β±2.22% (91 runs sampled)
  minimatch x 1,117,230 ops/sec Β±2.78% (86 runs sampled))

# .makeRe globstars
  micromatch x 1,658,642 ops/sec Β±0.86% (92 runs sampled)
  minimatch x 741,224 ops/sec Β±1.24% (89 runs sampled))

# .makeRe with leading star
  micromatch x 1,525,014 ops/sec Β±1.63% (90 runs sampled)
  minimatch x 561,074 ops/sec Β±3.07% (89 runs sampled)

# .makeRe - braces
  micromatch x 172,478 ops/sec Β±2.37% (78 runs sampled)
  minimatch x 96,087 ops/sec Β±2.34% (88 runs sampled)))

# .makeRe braces - range (expanded)
  micromatch x 26,973 ops/sec Β±0.84% (89 runs sampled)
  minimatch x 3,023 ops/sec Β±0.99% (90 runs sampled))

# .makeRe braces - range (compiled)
  micromatch x 152,892 ops/sec Β±1.67% (83 runs sampled)
  minimatch x 992 ops/sec Β±3.50% (89 runs sampled)d))

# .makeRe braces - nested ranges (expanded)
  micromatch x 15,816 ops/sec Β±13.05% (80 runs sampled)
  minimatch x 2,953 ops/sec Β±1.64% (91 runs sampled)

# .makeRe braces - nested ranges (compiled)
  micromatch x 110,881 ops/sec Β±1.85% (82 runs sampled)
  minimatch x 1,008 ops/sec Β±1.51% (91 runs sampled)

# .makeRe braces - set (compiled)
  micromatch x 134,930 ops/sec Β±3.54% (63 runs sampled))
  minimatch x 43,242 ops/sec Β±0.60% (93 runs sampled)

# .makeRe braces - nested sets (compiled)
  micromatch x 94,455 ops/sec Β±1.74% (69 runs sampled))
  minimatch x 27,720 ops/sec Β±1.84% (93 runs sampled))

Contributing

All contributions are welcome! Please read the contributing guide to get started.

Bug reports

Please create an issue if you encounter a bug or matching behavior that doesn't seem correct. If you find a matching-related issue, please:

  • research existing issues first (open and closed)
  • visit the GNU Bash documentation to see how Bash deals with the pattern
  • visit the minimatch documentation to cross-check expected behavior in node.js
  • if all else fails, since there is no real specification for globs we will probably need to discuss expected behavior and decide how to resolve it. which means any detail you can provide to help with this discussion would be greatly appreciated.

Platform issues

It's important to us that micromatch work consistently on all platforms. If you encounter any platform-specific matching or path related issues, please let us know (pull requests are also greatly appreciated).

About

Contributing

Pull requests and stars are always welcome. For bugs and feature requests, please create an issue.

Please read the contributing guide for advice on opening issues, pull requests, and coding standards.

Running Tests

Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command:

$ npm install && npm test
Building docs

(This project's readme.md is generated by verb, please don't edit the readme directly. Any changes to the readme must be made in the .verb.md readme template.)

To generate the readme, run the following command:

$ npm install -g verbose/verb#dev verb-generate-readme && verb

Related projects

You might also be interested in these projects:

  • braces: Bash-like brace expansion, implemented in JavaScript. Safer than other brace expansion libs, with complete support… more | homepage
  • expand-brackets: Expand POSIX bracket expressions (character classes) in glob patterns. | homepage
  • extglob: Extended glob support for JavaScript. Adds (almost) the expressive power of regular expressions to glob… more | homepage
  • fill-range: Fill in a range of numbers or letters, optionally passing an increment or step to… more | homepage
  • nanomatch: Fast, minimal glob matcher for node.js. Similar to micromatch, minimatch and multimatch, but complete Bash… more | homepage

Contributors

CommitsContributor
523jonschlinkert
12es128
9danez
8doowb
6paulmillr
5mrmlnc
3DrPizza
2Tvrqvoise
2antonyk
2MartinKolarik
2Glazy
2mceIdo
2TrySound
1yvele
1wtgtybhertgeghgtwtg
1simlu
1curbengh
1fidian
1tomByrer
1ZoomerTedJackson
1styfle
1sebdeckers
1muescha
1juszczykjakub
1joyceerhl
1donatj
1frangio
1UltCombo
1DianeLooney
1devongovett
1Cslove
1amilajack

Author

Jon Schlinkert

License

Copyright Β© 2024, Jon Schlinkert. Released under the MIT License.


This file was generated by verb-generate-readme, v0.8.0, on August 23, 2024.