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.
Ugh, yet another file traversal thing on npm?
Yes. None of the existing ones gave me exactly what I wanted.
Well what is it you wanted?
While working on glob, I found that I
needed a module to very efficiently manage the traversal over a
folder tree, such that:
- No
readdir() or stat() would ever be called on the same
file or directory more than one time.
- 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.)
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).
- 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.
- 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.
- Do not blow up the JS heap allocation if operating on a
directory with a huge number of entries.
- 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.
PERFORMANCE
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.
Resolving paths
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.
Walking directory trees
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.
Which walk is the fastest?
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:
- A manual recursive walk with
entry.readdirSync().
pw.walkSync().
- A manual walk with
entry.readdirCB(cb, true).
pw.iterateSync().
- A manual walk with
entry.readdirCB(cb).
pw.walk().
pw.iterateBatches().
- A manual walk with
await entry.readdir().
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.
How it goes fast
- 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.
USAGE
// 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)
API
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.
Interface PathScurryOpts
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
Interface WalkOptions
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.
Class PathScurry
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.
async pw.walk(entry?: string | Path | WalkOptions, opts?: WalkOptions)
Walk the directory tree according to the options provided,
resolving to an array of all entries found.
pw.walkSync(entry?: string | Path | WalkOptions, opts?: WalkOptions)
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.
pw.iterate(entry?: string | Path | WalkOptions, opts?: WalkOptions)
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()).
pw.iterateBatches(entry?: string | Path | WalkOptions, opts?: WalkOptions)
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.