Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@jeffmcmahan
Last active August 29, 2015 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeffmcmahan/11200724 to your computer and use it in GitHub Desktop.
Save jeffmcmahan/11200724 to your computer and use it in GitHub Desktop.
Recursively, asynchronously read directories in Node.js
// Calling reAsyncReaddir("file/path", callback) passes an object composed of
// a "files" array and a "directories" array (=keys) to your callback.
var fs = require("fs");
var results = {
"files" : [],
"directories" : []
};
var counts = {
"fsObjects" : 0,
"readdir" : 0
};
var checkCount = function (callback) {
if (!counts.fsObjects && !counts.readdir) {
callback(results);
}
};
var checkStat = function (path, callback) {
fs.stat(path, function (err, stats) {
if (stats.isDirectory()) {
reAsyncReaddir(path, callback);
results.directories.push(path);
} else {
results.files.push(path);
}
counts.fsObjects--;
checkCount(callback);
});
};
var reAsyncReaddir = function (path, callback) {
var counter = 0;
counts.readdir++;
fs.readdir(path, function (err, data) {
if (!err) {
counts.fsObjects += data.length;
while (counter < data.length) {
checkStat(path + "/" + data[counter], callback);
counter++;
if (counter === data.length) {
counts.readdir--;
}
}
}
});
};
// Example callback function.
var complete = function (results) {
console.log(results);
};
// Don't include a trailing slash in the folder path.
reAsyncReaddir("example/folder/path", complete);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment