Skip to content

Instantly share code, notes, and snippets.

@alexyoung
Created August 16, 2010 22:34
Show Gist options
  • Save alexyoung/527880 to your computer and use it in GitHub Desktop.
Save alexyoung/527880 to your computer and use it in GitHub Desktop.
// Asynchronously recursively reads files
function RecursiveReader(pathName, callback) {
this.filesLeft = 1;
this.pathName = pathName;
this.callback = callback;
this.data = '';
this.readAll(this.pathName);
}
RecursiveReader.prototype = {
readAll: function(pathName) {
var rr = this;
fs.readdir(pathName, function(err, files) {
rr.filesLeft -= 1;
rr.filesLeft += files.length;
files.forEach(function(fileName) {
fileName = path.join(pathName, fileName);
fs.stat(fileName, function(err, stats) {
if (stats && stats.isDirectory()) {
return rr.readAll(fileName);
} else {
fs.readFile(fileName, function(err, contents) {
rr.data += contents;
rr.filesLeft -= 1;
if (rr.filesLeft === 0) {
rr.callback(rr.data);
}
});
}
});
});
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment