path-scurry
    Preparing search index...

    path-scurry

    path-scurry

    Extremely high performant utility for building tools that read the file system, minimizing filesystem and path string munging operations to the greatest degree possible.

    Yes. None of the existing ones gave me exactly what I wanted.

    While working on glob, I found that I needed a module to very efficiently manage the traversal over a folder tree, such that:

    1. No readdir() or stat() would ever be called on the same file or directory more than one time.
    2. No readdir() calls would be made if we can be reasonably sure that the path is not a directory. (Ie, a previous readdir() or stat() covered the path, and ent.isDirectory() is false.)
    3. path.resolve(), dirname(), basename(), and other string-parsing/munging operations are be minimized. This means it has to track "provisional" child nodes that may not exist (and if we find that they don't exist, store that information as well, so we don't have to ever check again).
    4. The API is not limited to use as a stream/iterator/etc. There are many cases where an API like node's fs is preferrable.
    5. It's more important to prevent excess syscalls than to be up to date, but it should be smart enough to know what it doesn't know, and go get it seamlessly when requested.
    6. Do not blow up the JS heap allocation if operating on a directory with a huge number of entries.
    7. Handle all the weird aspects of Windows paths, like UNC paths and drive letters and wrongway slashes, so that the consumer can return canonical platform-specific paths without having to parse or join or do any error-prone string munging.

    JavaScript people throw around the word "blazing" a lot. I hope that this module doesn't blaze anyone. But it does go very fast, in the cases it's optimized for, if used properly.

    PathScurry provides ample opportunities to get extremely good performance, as well as several options to trade performance for convenience.

    Benchmarks can be run by executing npm run bench.

    As is always the case, doing more means going slower, doing less means going faster, and there are trade offs between speed and memory usage.

    PathScurry caches whatever it can, and Path objects remain in the graph for the lifetime of the walker, so repeated calls with a single PathScurry object will be extremely fast. However, adding items to a cold cache means "doing more", so in those cases, we pay a price. Nothing is free, but every effort has been made to reduce costs wherever possible.

    Also, note that a "cache as long as possible" approach means that changes to the filesystem may not be reflected in the results of repeated PathScurry operations.

    For resolving string paths, PathScurry ranges from 2-25 times faster than path.resolve on repeated resolutions, but around 2 to 5 times slower on the first resolution. If your program is spending a lot of time resolving the same paths repeatedly (like, thousands or millions of times), then this can be beneficial. But both implementations are pretty fast, and speeding up an infrequent operation from 1µs to 100ns is not going to move the needle on your app's performance.

    A directory with 16 or more known entries finds a child by name in an index, so resolving many paths in one large directory takes linear time.

    For walking file system directory trees, a lot depends on how often a given PathScurry object will be used, and also on the walk method used.

    With default settings on a folder tree of 100,000 items, consisting of around a 10-to-1 ratio of normal files to directories, PathScurry performs comparably to @nodelib/fs.walk, which is the fastest and most reliable file system walker I could find. As far as I can tell, it's almost impossible to go much faster in a Node.js program, just based on how fast you can push syscalls out to the fs thread pool.

    # walk 100,000 fs entries, 10/1 file/dir ratio
    # entries / ms
    New PathScurry object | Reuse PathScurry object
    async walk: 1004.604 | 87623.383
    sync walk: 414.778 | 179747.926
    async iter: 1232.055 | 16672.783
    async batches: 1011.069 | 69277.746
    sync iter: 421.646 | 108868.573

    On my machine, a cold walk of that tree takes about 80 to 100ms with the async methods, and about 240ms with the sync methods.

    In the warm cache state, PathScurry's performance increases around 13x for async for await iteration by entry, 70x for async iteration by batch, 250x for synchronous for of iteration, 85x for an async walk, and 400x for a synchronous walk.

    A hand-rolled walk calling entry.readdir() and recursing through the entries can benefit even more from caching, with greater flexibility and without the overhead of iterators.

    The cold cache state is still limited by the costs of file system operations, but with a warm cache, the only bottleneck is CPU speed and VM optimizations. Of course, in that case, some care must be taken to ensure that you don't lose performance as a result of silly mistakes, like calling readdir() on entries that you know are not directories.

    # manual recursive iteration functions
    # entries / ms
    cold cache | warm cache
    async: 1206.922 | 36696.197
    cb: 1165.698 | 95744.807
    zalgo: 1162.885 | 150296.819
    sync: 428.603 | 239206.317

    In this case, the speed improves by around 30x in the async case, 80x in the case of using entry.readdirCB with protections against synchronous callbacks, 130x with callback deferrals disabled, and several hundred times faster for synchronous iteration.

    It depends on whether the cache is cold or warm.

    Cold cache (a new PathScurry, or a part of the tree that it has not read yet): use an async method. pw.walk(), pw.iterate(), pw.iterateBatches(), and a manual async walk all run at about the same speed, which is 2.5 to 3 times the speed of the sync methods. They read many directories at the same time on the fs thread pool, and the sync methods read one directory at a time. Almost all of the time goes to the file system, so the method that you use to get the results makes very little difference.

    • pw.iterate() is as fast as pw.walk(), and holds far fewer results in memory. It is the best default for a large tree.
    • A larger UV_THREADPOOL_SIZE does not help. On my machine (macOS, APFS), the default of 4 threads was the fastest. With 8 threads, a cold walk took 25% longer, and with 16 threads, it took twice as long.

    Warm cache (a PathScurry that has read the tree already): use a sync method. No file system calls occur, so the cost of promises, callbacks, and iterators is all that remains. From fastest to slowest:

    1. A manual recursive walk with entry.readdirSync().
    2. pw.walkSync().
    3. A manual walk with entry.readdirCB(cb, true).
    4. pw.iterateSync().
    5. A manual walk with entry.readdirCB(cb).
    6. pw.walk().
    7. pw.iterateBatches().
    8. A manual walk with await entry.readdir().
    9. pw.iterate().

    If the full result is too large to hold in an array, use pw.iterateSync(), or pw.iterateBatches() if the walk must be async.

    pw.iterate() comes last, because for await takes one promise for each entry. pw.iterateBatches() gives an array of all the entries that are ready at each step, so it takes far fewer promises, and is about 4 times as fast on a warm cache.

    In both states:

    • The default follow: false is faster. With follow: true, the walk calls realpath on each symbolic link, and keeps a Set of all the directories that it found.
    • withFileTypes: false is slightly slower, because the walk makes the full path string for each entry.
    • filter and walkFilter functions are called one time for each entry, so keep them cheap.
    • It has no dependencies.
    • Each directory holds an array of its child entries. A two-generation cache limits how many directories keep that array, so a lookup is a field read, and old directories drop their children when the cache turns over. See childrenCacheSize below.
    • The entries of a directory are added in linear time, so a directory with a huge number of entries costs the same per entry as a small one.
    • File names that are all ASCII skip unicode normalization.
    • All Path objects under the same root share one object for the settings that they have in common, which keeps each Path small.
    • pw.iterate() and pw.iterateBatches() read directories ahead of the consumer, and wait when they hold 1024 entries that the consumer has not taken yet. Thus, a slow consumer limits memory use, and a fast one does not wait for each directory.
    • The iterators are plain objects with a next() method, not generator functions.

    If you can think of a case that is not covered in these benchmarks, or an implementation that performs significantly better than PathScurry, please let me know.

    // hybrid module, load with either method
    import { PathScurry, Path } from 'path-scurry'
    // or:
    const { PathScurry, Path } = require('path-scurry')

    // very simple example, say we want to find and
    // delete all the .DS_Store files in a given path
    // note that the API is very similar to just a
    // naive walk with fs.readdir()
    import { unlink } from 'fs/promises'

    // easy way, iterate over the directory and do the thing
    const pw = new PathScurry(process.cwd())
    for await (const entry of pw) {
    if (entry.isFile() && entry.name === '.DS_Store') {
    unlink(entry.fullpath())
    }
    }

    // here it is as a manual recursive method
    const walk = async (entry: Path) => {
    const promises: Promise<any> = []
    // readdir doesn't throw on non-directories, it just doesn't
    // return any entries, to save stack trace costs.
    // Items are returned in arbitrary unsorted order
    for (const child of await pw.readdir(entry)) {
    // each child is a Path object
    if (child.name === '.DS_Store' && child.isFile()) {
    // could also do pw.resolve(entry, child.name),
    // just like fs.readdir walking, but .fullpath is
    // a *slightly* more efficient shorthand.
    promises.push(unlink(child.fullpath()))
    } else if (child.isDirectory()) {
    promises.push(walk(child))
    }
    }
    return Promise.all(promises)
    }

    walk(pw.cwd).then(() => {
    console.log('all .DS_Store files removed')
    })

    const pw2 = new PathScurry('/a/b/c') // pw2.cwd is the Path for /a/b/c
    const relativeDir = pw2.cwd.resolve('../x') // Path entry for '/a/b/x'
    const relative2 = pw2.cwd.resolve('/a/b/d/../x') // same path, same entry
    assert.equal(relativeDir, relative2)

    Full TypeDoc API

    There are platform-specific classes exported, but for the most part, the default PathScurry and Path exports are what you most likely need, unless you are testing behavior for other platforms.

    Intended public API is documented here, but the full documentation does include internal types, which should not be accessed directly.

    The type of the options argument passed to the PathScurry constructor.

    • nocase: Boolean indicating that file names should be compared case-insensitively. Defaults to true on darwin and win32 implementations, false elsewhere.

      Warning Performing case-insensitive matching on a case-sensitive filesystem will result in occasionally very bizarre behavior. Performing case-sensitive matching on a case-insensitive filesystem may negatively impact performance.

    • childrenCacheSize: Number of directories that always keep their list of child entries, in order to speed up resolve() and readdir() calls. Up to twice this number can keep them. Defaults to 16 * 1024 (ie, 16384).

      Setting it to a higher value will run the risk of JS heap allocation errors on large directory trees. Setting it to 256 or smaller will reduce the data consumption overhead, but with the downside of operations being slower on large directory trees. Setting it to 0 will mean that effectively no operations are cached, and this module will be roughly the same speed as fs for file system operations, and slower than path.resolve() for repeated path resolution.

    • fs An object that will be used to override the default fs methods. Any methods that are not overridden will use Node's built-in implementations.

      • lstatSync
      • readdir (callback withFileTypes Dirent variant, used for readdirCB and most walks)
      • readdirSync
      • readlinkSync
      • realpathSync
      • promises: Object containing the following async methods:
        • lstat
        • readdir (Dirent variant only)
        • readlink
        • realpath

    The options object that may be passed to all walk methods.

    • withFileTypes: Boolean, default true. Indicates that Path objects should be returned. Set to false to get string paths instead.

    • follow: Boolean, default false. Attempt to read directory entries from symbolic links. Otherwise, only actual directories are traversed. Regardless of this setting, a given target path will only ever be walked once, meaning that a symbolic link to a previously traversed directory will never be followed.

      Setting this imposes a slight performance penalty, because readlink must be called on all symbolic links encountered, in order to avoid infinite cycles.

    • filter: Function (entry: Path) => boolean. If provided, will prevent the inclusion of any entry for which it returns a falsey value. This will not prevent directories from being traversed if they do not pass the filter, though it will prevent the directories themselves from being included in the results. By default, if no filter is provided, then all entries are included in the results.

    • walkFilter: Function (entry: Path) => boolean. If provided, will prevent the traversal of any directory (or in the case of follow:true symbolic links to directories) for which the function returns false. This will not prevent the directories themselves from being included in the result set. Use filter for that.

    Note that TypeScript return types will only be inferred properly from static analysis if the withFileTypes option is omitted, or a constant true or false value.

    The main interface. Defaults to an appropriate class based on the current platform.

    Use PathScurryWin32, PathScurryDarwin, or PathScurryPosix if implementation-specific behavior is desired.

    All walk methods may be called with a WalkOptions argument to walk over the object's current working directory with the supplied options.

    Walk the directory tree according to the options provided, resolving to an array of all entries found.

    Walk the directory tree according to the options provided, returning an array of all entries found.

    This is the fastest walk method when the cache is warm.

    Iterate over the directory asynchronously, for use with for await of. This is also the default async iterator method.

    The walk starts on the first call to next(). It reads directories ahead of the consumer, and waits when it holds 1024 entries that the consumer has not taken yet.

    On a cold cache, this is as fast as pw.walk(), and uses less memory.

    To get a stream, use Readable.from(pw.iterate()).

    The same walk as pw.iterate(), but each step gives an array of all the entries that are ready, instead of one entry.

    for await (const batch of pw.iterateBatches()) {
    for (const entry of batch) {
    // ...
    }
    }

    The arrays are never empty. An array can hold the entries of more than one directory, and a large directory can add more than 1024 entries to one array.

    On a warm cache, this is about 4 times as fast as pw.iterate(), because it makes one promise for each array instead of one for each entry. On a cold cache, the two are the same speed.

    Iterate over the directory synchronously, for use with for of. This is also the default sync iterator method.

    Path object representing the current working directory for the PathScurry.

    Set the new effective current working directory for the scurry object, so that path.relative() and path.relativePosix() return values relative to the new cwd path.

    Return the depth of the specified path (or the PathScurry cwd) within the directory tree.

    Root entries have a depth of 0.

    Caching path.resolve().

    Significantly faster than path.resolve() if called repeatedly with the same paths. Significantly slower otherwise, as it builds out the cached Path entries.

    To get a Path object resolved from the PathScurry, use pw.cwd.resolve(path). Note that Path.resolve only takes a single string argument, not multiple.

    Caching path.resolve(), but always using posix style paths.

    This is identical to pw.resolve(...paths) on posix systems (ie, everywhere except Windows).

    On Windows, it returns the full absolute UNC path using / separators. Ie, instead of 'C:\\foo\\bar, it would return //?/C:/foo/bar.

    Return the relative path from the PathWalker cwd to the supplied path string or entry.

    If the nearest common ancestor is the root, then an absolute path is returned.

    Return the relative path from the PathWalker cwd to the supplied path string or entry, using / path separators.

    If the nearest common ancestor is the root, then an absolute path is returned.

    On posix platforms (ie, all platforms except Windows), this is identical to pw.relative(path).

    On Windows systems, it returns the resulting string as a /-delimited path. If an absolute path is returned (because the target does not share a common ancestor with pw.cwd), then a full absolute UNC path will be returned. Ie, instead of 'C:\\foo\\bar, it would return //?/C:/foo/bar.

    Return the basename of the provided string or Path.

    Return the parent directory of the supplied string or Path.

    Read the directory and resolve to an array of strings if withFileTypes is explicitly set to false or Path objects otherwise.

    Can be called as pw.readdir({ withFileTypes: boolean }) as well.

    Returns [] if no entries are found, or if any error occurs.

    Note that TypeScript return types will only be inferred properly from static analysis if the withFileTypes option is omitted, or a constant true or false value.

    Synchronous pw.readdir()

    Call fs.readlink on the supplied string or Path object, and return the result.

    Can be called as pw.readlink({ withFileTypes: boolean }) as well.

    Returns undefined if any error occurs (for example, if the argument is not a symbolic link), or a Path object if withFileTypes is explicitly set to true, or a string otherwise.

    Note that TypeScript return types will only be inferred properly from static analysis if the withFileTypes option is omitted, or a constant true or false value.

    Synchronous pw.readlink()

    Call fs.lstat on the supplied string or Path object, and fill in as much information as possible, returning the updated Path object.

    Returns undefined if the entry does not exist, or if any error is encountered.

    Note that some Stats data (such as ino, dev, and mode) will not be supplied. For those things, you'll need to call fs.lstat yourself.

    Synchronous pw.lstat()

    Call fs.realpath on the supplied string or Path object, and return the realpath if available.

    Returns undefined if any error occurs.

    May be called as pw.realpath({ withFileTypes: boolean }) to run on pw.cwd.

    Synchronous pw.realpath()

    Object representing a given path on the filesystem, which may or may not exist.

    Note that the actual class in use will be either PathWin32 or PathPosix, depending on the implementation of PathScurry in use. They differ in the separators used to split and join path strings, and the handling of root paths.

    In PathPosix implementations, paths are split and joined using the '/' character, and '/' is the only root path ever in use.

    In PathWin32 implementations, paths are split using either '/' or '\\' and joined using '\\', and multiple roots may be in use based on the drives and UNC paths encountered. UNC paths such as //?/C:/ that identify a drive letter, will be treated as an alias for the same root entry as their associated drive letter (in this case 'C:\\').

    Name of this file system entry.

    Important: always test the path name against any test string using the isNamed method, and not by directly comparing this string. Otherwise, unicode path strings that the system sees as identical will not be properly treated as the same path, leading to incorrect behavior and possible security issues.

    Return true if the path is a match for the given path name. This handles case sensitivity and unicode normalization.

    Note: even on case-sensitive systems, it is not safe to test the equality of the .name property to determine whether a given pathname matches, due to unicode normalization mismatches.

    Always use this method instead of testing the path.name property directly.

    Set to true if this Path object is the current working directory of the PathScurry collection that contains it.

    Returns the type of the Path object, 'File', 'Directory', etc.

    Returns true if is{t}() returns true.

    For example, path.isType('Directory') is equivalent to path.isDirectory().

    Return the depth of the Path entry within the directory tree. Root paths have a depth of 0.

    The fully resolved path to the entry.

    The fully resolved path to the entry, using / separators.

    On posix systems, this is identical to path.fullpath(). On windows, this will return a fully resolved absolute UNC path using / separators. Eg, instead of 'C:\\foo\\bar', it will return '//?/C:/foo/bar'.

    Same as the identical fs.Dirent.isX() methods.

    Returns true if the path's type is unknown. Always returns true when the path is known to not exist.

    Return a Path object associated with the provided path string as resolved from the current Path object.

    Return the relative path from the PathWalker cwd to the supplied path string or entry.

    If the nearest common ancestor is the root, then an absolute path is returned.

    Return the relative path from the PathWalker cwd to the supplied path string or entry, using / path separators.

    If the nearest common ancestor is the root, then an absolute path is returned.

    On posix platforms (ie, all platforms except Windows), this is identical to pw.relative(path).

    On Windows systems, it returns the resulting string as a /-delimited path. If an absolute path is returned (because the target does not share a common ancestor with pw.cwd), then a full absolute UNC path will be returned. Ie, instead of 'C:\\foo\\bar, it would return //?/C:/foo/bar.

    Return an array of Path objects found by reading the associated path entry.

    If path is not a directory, or if any error occurs, returns [], and marks all children as provisional and non-existent.

    Synchronous path.readdir()

    Read the directory, and return a DirEntries object. It does not make a Path object for each entry, so it is faster when most of the entries only need a test of their name or type.

    const entries = pw.cwd.readdirLazySync()
    for (let i = 0; i < entries.length; i++) {
    if (entries.name(i).endsWith('.js') && !entries.isDirectory(i)) {
    // makes the Path object for this entry only
    console.log(entries.path(i).fullpath())
    }
    }

    If path is not a directory, or if any error occurs, the object has no entries.

    The same as path.readdirLazySync(), but asynchronous. The callback gets the DirEntries object as its only argument.

    If allowZalgo is true, and the entries are in the cache, then the callback runs before the method returns.

    Return the Path object referenced by the path as a symbolic link.

    If the path is not a symbolic link, or any error occurs, returns undefined.

    Synchronous path.readlink()

    Call lstat on the path object, and fill it in with details determined.

    If path does not exist, or any other error occurs, returns undefined, and marks the path as "unknown" type.

    Synchronous path.lstat()

    Call realpath on the path, and return a Path object corresponding to the result, or undefined if any error occurs.

    Synchornous path.realpath()

    The entries of a directory. An entry is a number i, from 0 up to, but not including, entries.length.

    • entries.dir The Path object of the directory.
    • entries.length The count of entries.
    • entries.name(i) The name of the entry.
    • entries.path(i) The Path object of the entry. The first call makes the object.
    • entries.cached(i) The Path object of the entry, or undefined if nothing made it yet.
    • entries.isNamed(i, name), entries.isUnknown(i), entries.isDirectory(i), entries.isSymbolicLink(i), entries.canReaddir(i) The same answer as the Path method of that name, without the Path object.