Glob File Matching Utility

13.0.6 · active · verified Sun Apr 19

The `glob` package provides a robust and highly performant implementation for matching files using shell-like patterns in JavaScript. It is widely considered one of the most correct and fastest glob implementations available, supporting standard glob features such as wildcards, brace expansion, and extended globs. The current stable version is 13.0.6, and it targets modern Node.js environments (v18, v20, >=v22). The library emphasizes correctness according to shell standards and offers both synchronous and asynchronous APIs, including stream-based operations and an advanced `Glob` object for optimized, re-usable pattern matching. A key differentiator is its `withFileTypes` option, which returns enhanced `Path` objects (similar to `fs.Dirent`) for rich file metadata access and manipulation, including custom sorting and filtering based on file stats. It is actively maintained with a regular release cadence for bug fixes and feature enhancements.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates asynchronous glob matching, multi-pattern support, iteration with the `Glob` class, and retrieving detailed file type information with stats.

import { glob, Glob } from 'glob';
import { AbortSignal } from 'node:os'; // Or 'node-abort-controller' for older Node.js

async function runGlobExamples() {
  // Find all JavaScript files, ignoring node_modules
  console.log('Finding JS files (excluding node_modules)...');
  const jsFiles = await glob('**/*.js', { ignore: 'node_modules/**' });
  console.log('Found JS files:', jsFiles.slice(0, 5), '...');

  // Find images with multiple patterns
  console.log('\nFinding image files...');
  const images = await glob(['css/*.{png,jpeg}', 'public/*.{png,jpeg}']);
  console.log('Found images:', images);

  // Using a Glob object for reusability and async iteration
  console.log('\nIterating with Glob object for "**/foo"...');
  const g = new Glob('**/foo', {});
  let fooCount = 0;
  for await (const file of g) {
    console.log('Found foo file:', file);
    fooCount++;
    if (fooCount > 3) break; // Limit output for example
  }
  if (fooCount === 0) console.log('No foo files found in this example.');

  // Find files with detailed file types and stats, sorted by modification time
  console.log('\nFinding all files with stats, sorted by mtime...');
  const results = await glob('**', { stat: true, withFileTypes: true, nodir: true });
  const timeSortedFiles = results
    .sort((a, b) => a.mtimeMs - b.mtimeMs)
    .map(path => ({ path: path.fullpath(), mtime: new Date(path.mtimeMs).toLocaleTimeString() }))
    .slice(0, 5);
  console.log('Top 5 recently modified files:', timeSortedFiles);
}

runGlobExamples().catch(console.error);

view raw JSON →