adir
Utility for recursive aggregation of directory trees.
Useful for creating directory indices,
searching by file attributes,
performing calculations on a directory tree,
building routing tables dynamically, etc.
Usage
const aggregate = require('adir'),
tree = {}
function onEntry(stats, subtree) {
var name = stats.basename
if (stats.isDirectory())
return subtree[ name ] = {}
else
subtree[ name ] = stats.size
}
function done(err) {
if (err)
console.error(err.stack)
else
console.log(tree)
}
aggregate('./', onEntry, tree, done)
API
adir(path, onEntry, [initialValue], [callback])
⇒ Promise
adir.fs
: The file system interface to use.
adir.break
: Reference used to signal the end of an aggregation branch.
adir.version
: The version string from package manifest.
const fs = require('fs'),
adir = require('adir')
typeof adir === 'function'
adir.fs === fs
typeof adir.break === 'object'
typeof adir.version === 'string'
function onEntry(stats, value) {
stats instanceof fs.Stats
typeof stats.path === 'string'
typeof stats.basename === 'string'
value === 0
return value
}
function callback(err) {
err instanceof Error ||
err === null
}
adir('./', onEntry, 0, callback) instanceof Promise
How It Works?
adir
iterates over subdirectories of a folder and calls the given onEntry
handler on each directory or file,
taking an extended fs.Stats
instance and the value previously returned in the last invocation of onEntry
, or initialValue
, if supplied.
You can think of it like a kind of Array.prototype.reduce()
except the reduction forks when it meets a directory.
const aggregate = require('adir')
function onEntry(stats, count) {
if (stats.isDirectory())
return count + 1
else
console.log(stats.path, 'has', count, 'parent directories')
}
aggregate('./', onEntry, 0)
If onEntry
returns a Promise
then it'll be awaited before the aggregation of the corresponding branch continues. See this for a working example.
Cancellation
The aggregation of a branch stops immediately if onEntry
returns with adir.break
(or the Promise
returned by onEntry
resolves with that value).
This example shows that in action.
Compatibility
adir
is compatible with Node 0.8 and above but a Promise
implementation is required even if you're using the callback API only.
Tested with bluebird.
Installation
With npm:
npm install adir
License
MIT