find-up

repository·main·Indexed 20 days ago

https://github.com/sindresorhus/find-up

A utility for finding files or directories by walking up parent directories or down descendant directories. Version 8.0.0 provides asynchronous and synchronous functions including findUp(), findUpMultiple(), and findDown(), with support for custom matcher functions, search depth limits, and specific search strategies like breadth-first or depth-first.

Tokens
4.1K
Snippets
18
Records
22
Agent score
71%

What's inside find-up

  1. Use a matcher function to find paths

    main

    Instead of a string or array of strings, you can provide a matcher function to findUp or findDown methods. The matcher function is called with the current directory (cwd) as an argument.

    If the matcher function returns a string, that string is treated as a relative path to be located within the current directory. If it returns a path that doesn't exist, the search continues.

    To stop the search manually, the matcher function can return the findUpStop symbol.

    import {findUp, findUpStop} from 'find-up';
    
    const path = await findUp(async (cwd) => {
    	if (cwd.includes('special-dir')) {
    		return findUpStop;
    	}
    	return 'target.txt';
    });
  2. Find multiple files or directories by walking up with findUpMultiple()

    main

    Use findUpMultiple() to find all occurrences of a file or directory by walking up parent directories.

    • Returns a Promise that resolves to an Array of all paths found, or an empty array if none are found.
    • You can limit the number of results by setting the limit option.

    Returns a Promise that resolves to an Array<string>.

    // Returns an array of all matches found walking up
    const paths = await findUpMultiple('config.json', { limit: 5 });
  3. Find a file or directory by walking up parent directories with findUp()

    main

    Use findUp() to search for a file or directory by walking up from the current directory through parent directories.

    • If you provide a string, it searches for that specific name.
    • If you provide an Array<string>, it returns the first path found, respecting the order of the names in the array.
    • If you provide a matcher function, it calls the function for each directory. The matcher can return a path to match or a findUpStop symbol to halt the search.

    Returns a Promise that resolves to the path or undefined if not found.

    import {findUp} from 'find-up';
    
    // Find a single file
    console.log(await findUp('unicorn.png'));
    
    // Find the first match from an array of names
    console.log(await findUp(['rainbow.png', 'unicorn.png']));
    
    // Use a matcher function for advanced logic
    console.log(await findUp(async directory => {
    	const hasUnicorn = await pathExists(path.join(directory, 'unicorn.png'));
    	return hasUnicorn && directory;
    }, {type: 'directory'}));
  4. Find a file or directory by walking down descendant directories with findDown()

    main

    Use findDown() to search for a file or directory by walking down from the current directory into descendant directories.

    • Returns a Promise that resolves to the path or undefined if not found.
    • You can control the search depth using the depth option.
    • You can choose between 'breadth' (breadth-first) or 'depth' (depth-first) search strategies.
    import {findDown} from 'find-up';
    
    // Find a file in descendant directories
    console.log(await findDown('example.js'));
  5. Use synchronous versions of find-up functions

    main

    If you need to perform searches synchronously, use the following functions:

    • findUpSync(name, options?): Returns the path or undefined.
    • findUpMultipleSync(name, options?): Returns an array of all paths found or an empty array.
  6. Configure findUp and findDown options

    main

    Both findUp and findDown functions accept an options object to customize the search behavior.

    Common Options

    • cwd: The directory to start from. (Default: process.cwd()). Type: URL | string.
    • type: The type of path to match. Values: 'file' | 'directory' | 'both'. (Default: 'file').
    • allowSymlinks: Whether to allow symbolic links to match. (Default: true).

    findUp Specific Options

    • stopAt: A directory path where the search halts if no matches are found before reaching this point. Type: URL | string.

    findUpMultiple Specific Options

    • limit: The maximum number of matches to return. (Default: Infinity).

    findDown Specific Options

    • depth: Maximum number of directory levels to traverse below cwd. (Default: 1).
    • strategy: Search strategy to use. Values: 'breadth' (find shallower matches first) or 'depth' (fully explore branches). (Default: 'breadth').
  7. Find multiple files or directories upwards synchronously with findUpMultipleSync()

    main

    Use findUpMultipleSync() to find all occurrences of a file or directory as you traverse up the directory tree synchronously.

    Parameters:

    • name: A string, an array of strings, or a matcher function.
    • options: An optional object:
      • cwd: The directory to start searching from.
      • stopAt: A directory to stop searching at.
      • limit: The maximum number of matches to return.

    Returns a string[].

    import {findUpMultipleSync} from 'find-up';
    
    const paths = findUpMultipleSync('package.json');
    // returns an array of absolute paths for all package.json files found upwards
  8. Find a file or directory upwards with findUp()

    main

    Use findUp() to search for a file or directory by name, starting from a specified directory and moving up the directory tree towards the root. It returns the first match found or undefined if no match is found.

    Parameters:

    • name: A string, an array of strings, or a matcher function.
    • options: An optional object:
      • cwd: The directory to start searching from (defaults to current working directory).
      • stopAt: A directory to stop searching at (defaults to the filesystem root).
      • limit: The maximum number of matches to return (used internally by findUpMultiple).

    Returns a Promise<string | undefined>.

    import {findUp} from 'find-up';
    
    const path = await findUp('package.json');
    // returns the absolute path to the first package.json found upwards
  9. Find multiple files or directories upwards with findUpMultiple()

    main

    Use findUpMultiple() to find all occurrences of a file or directory as you traverse up the directory tree. This is useful when you want to find all instances of a configuration file in a project hierarchy.

    Parameters:

    • name: A string, an array of strings, or a matcher function.
    • options: An optional object:
      • cwd: The directory to start searching from.
      • stopAt: A directory to stop searching at.
      • limit: The maximum number of matches to return.

    Returns a Promise<string[]>.

    import {findUpMultiple} from 'find-up';
    
    const paths = await findUpMultiple('package.json');
    // returns an array of absolute paths for all package.json files found upwards
  10. Find a file or directory downwards with findDown()

    main

    Use findDown() to search for a file or directory by name, starting from a specified directory and searching through its subdirectories.

    Parameters:

    • name: A string, an array of strings, or a matcher function.
    • options: An optional object:
      • cwd: The directory to start searching from.
      • depth: The maximum depth to search (defaults to 1).
      • type: The type of entry to look for ('file' or 'directory').
      • allowSymlinks: Whether to follow symbolic links (defaults to true).
      • strategy: The search strategy: 'breadth' (default) or 'depth'.

    Returns a Promise<string | undefined>.

    import {findDown} from 'find-up';
    
    const path = await findDown('config.json', { depth: 2, strategy: 'depth' });
    // searches downwards from current directory up to 2 levels deep using depth-first search
  11. Find a file or directory downwards synchronously with findDownSync()

    main

    Use findDownSync() to search for a file or directory by name, starting from a specified directory and searching through its subdirectories synchronously.

    Parameters:

    • name: A string, an array of strings, or a matcher function.
    • options: An optional object:
      • cwd: The directory to start searching from.
      • depth: The maximum depth to search.
      • type: The type of entry to look for ('file' or 'directory').
      • allowSymlinks: Whether to follow symbolic links.
      • strategy: The search strategy: 'breadth' (default) or 'depth'.

    Returns a string | undefined.

    import {findDownSync} from 'find-up';
    
    const path = findDownSync('config.json', { depth: 2 });