Last active
August 29, 2015 14:00
-
-
Save jeffmcmahan/11200724 to your computer and use it in GitHub Desktop.
Recursively, asynchronously read directories in Node.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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