Skip to content

Instantly share code, notes, and snippets.

@svanellewee
Last active August 29, 2015 14:04
Show Gist options
  • Save svanellewee/496b3cdbad464f85d059 to your computer and use it in GitHub Desktop.
Save svanellewee/496b3cdbad464f85d059 to your computer and use it in GitHub Desktop.
Got confused with other people's async walk examples... so created my own.
var fs = require("fs")
var path = require("path"); //extname, resolve
var pp= console.log
var FILEPATH = "/home/stephan/Music"
// verify with "ls ~/Music/ |wc -l" in one folder
// "find ~/Music/ -type f | wc -l" recursively!!!
function walk(root_path) {
var total_results = [];
var thread_count = 0; // OH NOES! I used the word "thread" in node code! Blasphemy!
// to be fair though, that's what it eventually becomes.
(function readdir(target_path) {
thread_count += 1;
fs.readdir(target_path,
function(err, fsitems) {
var results = []
var total_items = fsitems.length;
fsitems.forEach(function(item) {
item = path.resolve(target_path, item);
if (!fs.statSync(item).isDirectory()) {
results.push(item);
} else {
readdir(item);
}
if(!--total_items) {
total_results = total_results.concat(results);
thread_count -= 1;
}
});
if (!thread_count)
pp(total_results); // verify with "find ~/Music/ -type f | wc -l"
});
})(root_path);
}
var b = walk(FILEPATH)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment