Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save thedjinn/530284 to your computer and use it in GitHub Desktop.
Save thedjinn/530284 to your computer and use it in GitHub Desktop.
require("./walk").walk(
"/path/to/a/directory",
function(file) {
console.log(file);
},
function(err) {
if(err) throw err;
console.log("Finished.");
}
);
var fs = require("fs");
var path = require("path");
exports.walk = (function() {
var counter = 0;
var walk = function(dirname, callback, finished) {
counter += 1;
fs.readdir(dirname, function(err, relnames) {
if(err) {
finished(err);
return;
}
if (relnames.length === 0) counter -= 1;
relnames.forEach(function(relname, index, relnames) {
var name = path.join(dirname, relname);
counter += 1;
fs.stat(name, function(err, stat) {
if(err) {
finished(err);
return;
}
if(stat.isDirectory()) {
exports.walk(name, callback, finished);
} else {
callback(name);
}
counter -= 1;
if(index === relnames.length - 1) counter -= 1;
if(counter === 0) {
finished(null);
}
});
});
});
};
return walk;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment