mkdirp

repository·main·Indexed 41 days ago

https://github.com/isaacs/node-mkdirp

A Node.js implementation of the `mkdir -p` command for recursive directory creation. Version 3.0.1 provides asynchronous Promise-based and synchronous APIs, a CLI tool, and support for both native Node.js recursive directory creation and a manual fallback implementation. It allows configuration via MkdirpOptions to specify directory modes and custom filesystem providers.

Tokens
2.1K
Snippets
10
Records
12
Agent score
52%

What's inside mkdirp

  1. Install mkdirp

    main

    You can install mkdirp via npm to use it as a library or as a CLI tool.

    To install it locally in your project:

    npm install mkdirp

    To install it globally to use the mkdirp command anywhere:

    npm install -g mkdirp

    To run the command without installing it globally:

    npx mkdirp ...
  2. Use mkdirp asynchronously with Promises

    main

    The mkdirp function returns a Promise that resolves to the first directory created, or undefined if the directory already exists. If an error occurs, the Promise rejects. Note that directory creation is not atomic, so some directories may have been created before a rejection occurs.

    import { mkdirp } from 'mkdirp'
    
    // The return value is a Promise resolving to the first directory created
    mkdirp('/tmp/foo/bar/baz').then(made =>
      console.log(`made directories, starting with ${made}`)
    )
    import { mkdirp } from 'mkdirp'
    
    mkdirp('/tmp/foo/bar/baz').then(made =>
      console.log(`made directories, starting with ${made}`)
    )
  3. Use mkdirp.sync for synchronous directory creation

    main

    If you prefer synchronous execution, use mkdirp.sync. It returns the first directory that had to be created, or undefined if the path already exists.

    import { mkdirp } from 'mkdirp'
    
    // The return value is the first directory created
    const made = mkdirp.sync('/tmp/foo/bar/baz')
    console.log(`made directories, starting with ${made}`)
    import { mkdirp } from 'mkdirp'
    
    const made = mkdirp.sync('/tmp/foo/bar/baz')
    console.log(`made directories, starting with ${made}`)
  4. Switch between manual and native implementations

    main

    mkdirp provides methods to explicitly choose the underlying implementation strategy:

    • mkdirp.native / mkdirp.nativeSync: Forces the use of the native Node.js fs.mkdir(path, { recursive: true }) implementation. This is the default behavior when available and no methods are overridden.
    • mkdirp.manual / mkdirp.manualSync: Forces the use of the manual implementation. This is the default when the native implementation is unavailable or when stat/mkdir methods have been overridden.
  5. Configure mkdirp options

    main

    The mkdirp functions accept an options argument of type MkdirpOptions. This allows you to specify the directory mode, provide a custom filesystem provider, or override asynchronous methods.

    Supported formats for MkdirpOptions:

    • Object: { mode?: number | string, fs?: FsProvider, mkdirAsync?: Function, statAsync?: Function }
    • Number: A numeric value representing the directory mode (e.g., 0o777).
    • String: An octal string representing the directory mode (e.g., '777').

    If no options are provided, the default mode is 0o777.

    // Using an object
    const options = { mode: 0o755 };
    
    // Using a number
    const options = 0o755;
    
    // Using an octal string
    const options = '755';
  6. Configure mkdirp with MkdirpOptions

    main

    Both mkdirp and mkdirp.sync accept an optional opts object of type MkdirpOptions:

    • mode: An octal permission string (e.g., '0o777'). If opts is passed as a string or number directly, it is treated as the mode. Defaults to 0o777.
    • fs: An alternate fs implementation.
      • For async mkdirp, the implementation must have fs.mkdir(path, opts, cb) and fs.stat(path, cb).
      • For sync mkdirp.sync, the implementation must have fs.mkdirSync(path, mode) and fs.statSync(path).
    • stat / statSync: Override the stat method.
    • mkdir / mkdirSync: Override the mkdir method.
    • mkdir / mkdirSync (inside fs object): You can provide an fs object that only overrides one of these methods.
  7. Use the mkdirp CLI

    main

    The mkdirp command creates supplied directories and any necessary parent directories. If a directory already exists, it does nothing.

    Usage: mkdirp [DIR1,DIR2..] {OPTIONS}

    Options:

    • -m<mode> or --mode=<mode>: Set the directory mode as an octal permission string if a directory needs to be created.
    • -v or --version: Print the version number.
    • -h or --help: Print the help banner.
    • -p or --print: Print the first directories created for each path provided.
    • --manual: Use the manual implementation even if native is available.
    $ mkdirp -h
    
    usage: mkdirp [DIR1,DIR2..] {OPTIONS}
    
      Create each supplied directory including any necessary parent directories
      that don't yet exist.
    
      If the directory already exists, do nothing.
    
    OPTIONS are:
    
      -m<mode>       If a directory needs to be created, set the mode as an octal
      --mode=<mode>  permission string.
    
      -v --version   Print the mkdirp version number
    
      -h --help      Print this helpful banner
    
      -p --print     Print the first directories created for each path provided
    
      --manual       Use manual implementation, even if native is available
  8. Use mkdirpNative and mkdirpManual implementations

    main

    You can bypass the automatic selection logic and explicitly choose an implementation strategy:

    • mkdirpNative / mkdirpNativeSync: Uses the native operating system implementation (e.g., mkdir -p).
    • mkdirpManual / mkdirpManualSync: Uses a manual implementation that traverses the path and creates directories step-by-step.
    import { mkdirp, mkdirpNative, mkdirpManual } from 'mkdirp';
    
    // Force native implementation
    await mkdirpNative('path/to/dir');
    
    // Force manual implementation
    await mkdirpManual('path/to/dir');
  9. Provide a custom filesystem provider

    main

    You can inject a custom filesystem implementation by passing an fs object (conforming to the FsProvider interface) within the options object. This is useful for mocking the filesystem in tests or using a specialized filesystem module.

    The FsProvider interface supports the following methods:

    • stat(path, callback)
    • mkdir(path, opts, callback)
    • statSync(path)
    • mkdirSync(path, opts)
    const customFs: FsProvider = {
      mkdirSync: (path, opts) => {
        // custom implementation
        return undefined;
      }
    };
    
    // Pass it to mkdirp
    await mkdirp('path/to/dir', { fs: customFs });
  10. Use mkdirp to create directories asynchronously

    main

    The primary way to use mkdirp is via the default asynchronous function. It creates a directory and all necessary parent directories. It automatically decides whether to use a native implementation or a manual implementation based on the provided options.

    import { mkdirp } from 'mkdirp';
    
    await mkdirp('path/to/directory');
  11. Reference: mkdirp API aliases

    main

    The mkdirp object provides several aliases for its methods to allow for different coding styles.

    // The following are available on the mkdirp object:
    
    // Asynchronous methods
    mkdirp.mkdirp(path, opts)
    mkdirp.native(path, opts)
    mkdirp.manual(path, opts)
    
    // Synchronous methods
    mkmkdirp.sync(path, opts)
    mkdirp.nativeSync(path, opts)
    mkdirp.manualSync(path, opts)
    
    // Utility methods
    mkdirp.useNative(opts)
    mkdirp.useNativeSync(opts)