Skip to content

Instantly share code, notes, and snippets.

@jcayzac
Created May 8, 2012 08:17
Show Gist options
  • Select an option

  • Save jcayzac/2633504 to your computer and use it in GitHub Desktop.

Select an option

Save jcayzac/2633504 to your computer and use it in GitHub Desktop.
var fs = require('fs');
/**
* Asynchronously build a tree corresponding to the specified directory.
*
* @param dir Root directory.
* @param cb Callback function with (err, tree) signature.
*/
function getFileTree(dir, cb) {
var results = {};
fs.readdir(dir, function(err, list) {
if (err) {
return cb(err);
}
var remaining = list.length;
if (!remaining) {
return cb(null, results);
}
list.forEach(function(file) {
var fullpath = dir + '/' + file,
addIt = function(err, res) {
results[file] = res;
if (--remaining === 0) {
cb(null, results);
}
};
fs.stat(fullpath, function(err, stat) {
if (stat && stat.isDirectory()) {
getFileTree(fullpath, addIt);
} else {
addIt(null, null);
}
});
});
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment