Skip to content

Instantly share code, notes, and snippets.

@xk
Created December 15, 2010 20:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xk/742540 to your computer and use it in GitHub Desktop.
Save xk/742540 to your computer and use it in GitHub Desktop.
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