Skip to content

Instantly share code, notes, and snippets.

@HoverBaum
Created July 4, 2016 02:22
Show Gist options
  • Save HoverBaum/2f21bc9c09cd30e61208926cd36b300b to your computer and use it in GitHub Desktop.
Save HoverBaum/2f21bc9c09cd30e61208926cd36b300b to your computer and use it in GitHub Desktop.
Asynchronously find all files matching a filter in a directory using node.
/**
* Walks a filestructure starting from a given root and returns all found files to a callback, using a filter.
* @param {String} dir - Root directory
* @param {RegEx} filter - RegEx to test found files against
* @param {Function} done - Callback will be called with (err, foundFiles)
* @private
*/
function walk(dir, filter, done) {
var results = [];
fs.readdir(dir, function(err, list) {
if (err) return done(err);
var pending = list.length;
if (!pending) return done(null, results);
list.forEach(function(file) {
file = path.resolve(dir, file);
fs.stat(file, function(err, stat) {
if (stat && stat.isDirectory()) {
walk(file, function(err, res) {
results = results.concat(res);
if (!--pending) done(null, results);
});
} else {
if (filter.test(file)) {
results.push(file);
}
if (!--pending) done(null, results);
}
});
});
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment