globby

repository·main·Indexed 25 days ago

https://github.com/sindresorhus/globby

A user-friendly glob matching library built on top of fast-glob. It provides a Promise API and advanced features including directory expansion, negation-only patterns, and support for .gitignore and other generic ignore files. It includes asynchronous (globby), synchronous (globbySync), and streaming (globbyStream) APIs, as well as utilities like convertPathToPattern, isGitIgnored, and generateGlobTasks.

Tokens
4.1K
Snippets
14
Records
31
Agent score
81%

What's inside globby

  1. Exclude files using negation patterns

    main

    You can exclude files from your results using negation patterns (starting with !). There are two ways to implement this:

    1. With positive patterns: Include positive patterns followed by negation patterns to filter the results.

    2. Negation-only patterns: If you provide only negation patterns, globby implicitly prepends **/* to match all files before applying the negations. For example, ['!*.json', '!*.xml'] is equivalent to ['**/*', '!*.json', '!*.xml'].

    Note: The implicit **/* pattern respects the dot option. By default, dotfiles (files starting with .) are not matched unless you set dot: true in the options.

    // Matches all .js files except test files
    await globby(['src/**/*.js', '!src/**/*.test.js']);
    
    // Matches all files in config/ except .json and .xml files
    await globby(['!*.json', '!*.xml'], {cwd: 'config'});
  2. Use globbing patterns for file matching

    main

    Globby uses standard globbing syntax to match files:

    • *: Matches any number of characters, but not /.
    • ?: Matches a single character, but not /.
    • **: Matches any number of characters, including / (must be the only thing in a path part).
    • {}: Allows for a comma-separated list of "or" expressions.
    • !: Negates the match when placed at the beginning of a pattern.
  3. Respect .gitignore files with gitignore option

    main

    Set gitignore: true (default is false) to respect ignore patterns in .gitignore files. Globby searches from the current working directory downwards and respects parent .gitignore files up to the Git repository root, matching standard Git behavior.

    Performance Tip: To read fewer ignore files, use ignoreFiles: '.gitignore' to target only the root ignore file.

  4. Configure expandDirectories in globby

    main

    The expandDirectories option controls how directories are handled:

    • true (default): Automatically globs directories.
    • Array: Only globs files matching the patterns in the array.
    • object: Allows fine-grained control using files and extensions.

    Note: If set to false, you won't get matched directories back unless you also set onlyFiles: false.

    import {globby} from 'globby';
    
    const paths = await globby('images', {
    	expandDirectories: {
    		files: ['cat', 'unicorn', '*.jpg'],
    		extensions: ['png']
    	}
    });
    
    console.log(paths);
    //=> ['cat.png', 'unicorn.png', 'cow.jpg', 'rainbow.jpg']
  5. Configure expandNegationOnlyPatterns

    main

    When providing only negation patterns (e.g., ['!*.json']), expandNegationOnlyPatterns (default true) automatically prepends **/* to match all files before applying negations. Set to false to return an empty array when only negation patterns are provided.

    import {globby} from 'globby';
    
    // Default behavior: matches all files except .json
    await globby(['!*.json']);
    
    // Disable expansion: returns empty array
    await globby(['!*.json'], {expandNegationOnlyPatterns: false});
  6. Use ignoreFiles for non-Git ignore files

    main
    The ignoreFiles option allows you to specify glob patterns to look for ignore files (like .babelignore, .prettierignore, or .eslintignore). This is a more generic version of the gitignore option.
  7. Use globalGitignore to respect global Git excludes

    main
    Set globalGitignore: true to respect ignore patterns in the global gitignore file configured via git config core.excludesfile. This includes support for [include] and gitdir sections in user-level config files.
  8. Use globby for glob matching

    main

    Import globby to match files using patterns. It supports multiple patterns, negated patterns (e.g., ['foo*', '!foobar']), and negation-only patterns (e.g., ['!foobar'] which matches all files except foobar). It also automatically expands directories (e.g., foo becomes foo/**/*) and supports .gitignore files.

    import {globby} from 'globby';
    
    const paths = await globby(['*', '!cake']);
    
    console.log(paths);
    //=> ['unicorn', 'rainbow']
  9. Check if a path is ignored by Git with isGitIgnored()

    main

    Returns a Promise<(path: URL | string) => boolean> that indicates whether a given path is ignored via a .gitignore file.

    Options:

    • cwd: The current working directory to search (default process.cwd()).
    • suppressErrors: If true, suppresses errors from unreadable directories/files.
    • deep: Maximum depth to search for .gitignore files (0, 1, 2, or Infinity).
    • ignore: Glob patterns to exclude from the .gitignore file search.
    • followSymbolicLinks: Whether to traverse descendants of symbolic link directories.
    • concurrency: Maximum number of concurrent requests to read directories.
    • throwErrorOnBrokenSymbolicLink: Whether to throw an error on broken symbolic links.
    • fs: Custom file system implementation.
    import {isGitIgnored} from 'globby';
    
    // Basic usage
    const isIgnored = await isGitIgnored();
    console.log(isIgnored('some/file'));
    
    // Suppress errors
    const isIgnoredWithErrorHandling = await isGitIgnored({suppressErrors: true});
    
    // Limit search depth and exclude certain directories
    const isIgnoredWithConstraints = await isGitIgnored({
    	deep: 2,
    	ignore: ['**/node_modules/**', '**/dist/**']
    });
  10. Convert a literal path to a glob pattern with convertPathToPattern()

    main

    Use convertPathToPattern(path) to escape special glob characters like (), [], and {}. On Windows, it also converts backslashes to forward slashes. This is necessary when your literal paths contain characters that have special meaning in glob syntax.

    import {globby, convertPathToPattern} from 'globby';
    
    // ✅ Works
    const base = convertPathToPattern('C:/Program Files (x86)');
    await globby(`${base}/*.txt`);
    //=> ['C:/Program Files (x86)/file.txt']