Skip to content

Instantly share code, notes, and snippets.

@xk xk/walkADir.js
Created Dec 15, 2010

Embed
What would you like to do?
walkADir.js
// 2010-12-15 jorge@jorgechamorro.com
// Uses 2 threads
function walk (file, cb) {
var fs = require('fs');
var e= {path:file, q:[]};
var q= [e];
begin();
function begin () {
fs.lstat(file, gotStat);
cb(file);
}
function gotStat (err, stat) {
if (err || !stat.isDirectory()) next();
else fs.readdir(file, gotDir);
}
function gotDir (err, files) {
if (err) throw Error(err);
files.sort(sort);
e= {path:file, q:files};
q.push(e);
next();
}
function next () {
if (e.q.length) {
file= [e.path, '/', e.q.pop()].join('');
begin();
}
else if (q.length-= 1) {
e= q[q.length- 1];
next();
}
}
function sort (a,b) {
a= a.toLowerCase();
b= b.toLowerCase();
return (a < b) ? 1 : (a > b) ? -1 : 0;
}
}
// your callback here
var ctr= 0;
function callBack (file) { console.log( ["[", ++ctr, "] ", file].join('') ) };
process.argv.forEach(function(val, index, array) {
if (index > 1) walk(val, callBack);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.