Created
December 15, 2010 20:14
-
-
Save xk/742540 to your computer and use it in GitHub Desktop.
walkADir.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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