recur-readdir
npm install recur-readdir
Recursively enumerate all files and directories within a directory.
Returns a Map
of absolute file paths to Node's fs.Stats
object.
const {crawl, crawlSync} = require('recur-readdir')
const {join} = require('path')
crawl(join(__dirname, 'testDir'))
.then(console.log, console.error)
Usage
- Async:
crawl
(returns a Promise) - Sync:
crawlSync
Pass in options as the second argument. Here are the defaults:
crawl(path, {
depth: Infinity,
filter: (path, stats) => true
})
Depth controls how deep to crawl. A depth of 0
returns
an empty map.
// Only get the files and directories immediately inside the target dir.
crawl(path, { depth: 1 })
Only files/dirs that satisfy the filter will be included in the results. The filter does not stop recursion.
For example, this crawl will ignore the .secret
directory
and return only files:
// .
// ├── a.txt
// ├── b.txt
// ├── nest1
// │ └── nest2
// │ └── nested.txt
// └── .secret
// └── password.txt
const filter = (path, stats) => {
return !path.includes('/.secret/') && stats.isFile()
}
crawl(path, { filter }).then(map => Array.from(map.keys()))
// ['/Users/user/example/a.txt', '/Users/user/example/b.txt', '/Users/user/example/nest1/nest2/nested.txt']
Why
Other published modules weren't general enough for me.
I didn't just want file nodes, and I wanted a generalized filter predicate.