Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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