Skip to content

Instantly share code, notes, and snippets.

@recidive
Created April 2, 2013 14:15
Show Gist options
  • Select an option

  • Save recidive/5292525 to your computer and use it in GitHub Desktop.

Select an option

Save recidive/5292525 to your computer and use it in GitHub Desktop.
A JavaScript/Node.js utility function to recurse a directory returning all files that ends with a suffix as a single dimensional array. Uses async library.
util.scan = function(dir, suffix, callback) {
fs.readdir(dir, function(err, files) {
var returnFiles = [];
async.each(files, function(file, next) {
var filePath = dir + '/' + file;
fs.stat(filePath, function(err, stat) {
if (err) {
return next(err);
}
if (stat.isDirectory()) {
util.scan(filePath, suffix, function(err, results) {
if (err) {
return next(err);
}
returnFiles = returnFiles.concat(results);
next();
})
}
else if (stat.isFile()) {
if (file.indexOf(suffix, file.length - suffix.length) !== -1) {
returnFiles.push(filePath);
}
next();
}
});
}, function(err) {
callback(err, returnFiles);
});
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment