diff options
author | isaacs <i@izs.me> | 2010-08-25 01:48:22 +0400 |
---|---|---|
committer | isaacs <i@izs.me> | 2010-08-25 16:21:50 +0400 |
commit | cbac60dba4090b10107ec0ec5bdb85f8274953b9 (patch) | |
tree | 4c3180c500f4e871217bca37eaceaca79ae6a445 | |
parent | ccc5c825dbbe8a7a3d19a9aa7f1461c1e6d7aa38 (diff) |
A simple async find type of thing
-rw-r--r-- | lib/utils/find.js | 41 |
1 files changed, 41 insertions, 0 deletions
diff --git a/lib/utils/find.js b/lib/utils/find.js new file mode 100644 index 000000000..a4567e421 --- /dev/null +++ b/lib/utils/find.js @@ -0,0 +1,41 @@ + +// walks a set of directories recursively, and returns +// the list of files that match the filter, if one is +// provided. + +module.exports = find +var fs = require("./graceful-fs") + , asyncMap = require("./async-map") + , path = require("path") + +function find (dir, filter, cb) { + if (!cb) cb = filter, filter = null + if (filter instanceof RegExp) filter = reFilter(filter) + if (!Array.isArray(dir)) dir = [dir] + asyncMap(dir, findDir(filter), cb) +} +function findDir (filter) { return function (dir, cb) { + fs.stat(dir, function (er, stats) { + // don't include missing files, but don't abort either + if (er) return cb() + if (!stats.isDirectory()) return cb(new Error( + "Not a dir, can't walk:"+dir)) + fs.readdir(dir, function (er, files) { + if (er) return cb(er) + asyncMap(files, findFile(dir, filter), cb) + }) + }) +}} +function findFile (dir, filter) { return function (f, cb) { + f = path.join(dir, f) + fs.stat(f, function (er, s) { + // don't include missing files, but don't abort either + if (er) return cb() + if (s.isDirectory()) return find(f, cb) + if (!filter || filter(f)) cb(null, f) + else cb() + }) +}} +function reFilter (re) { return function (f) { + return f.match(re) +}} |