Skip to content

Instantly share code, notes, and snippets.

@tim-smart
Forked from mikeal/gist:293922
Created February 3, 2010 19:42
Show Gist options
  • Save tim-smart/293938 to your computer and use it in GitHub Desktop.
Save tim-smart/293938 to your computer and use it in GitHub Desktop.
var http = require('http'),
sys = require('sys'),
path = require('path'),
posix = require('posix'),
events = require('events');
var Walker = function() {
this._counter = 0;
};
Walker.prototype = {
_listDir: function (pathname) {
var p = new events.Promise();
var ls = process.createChildProcess("ls", [pathname]);
ls.addListener("output", function (data) {
if (data) {
var files = [];
data.split('\n').forEach(function(f) {if (f){files.push(f)}});
p.emitSuccess(files)
}
});
return p;
},
walk: function (pathname, callback) {
var self = this;
this._listDir(pathname).addCallback(function(files) {
var dir = false;
files.forEach(function(f) {
self._counter++;
var abspath = path.join(pathname, f);
posix.stat(abspath).addCallback(function(stat) {
self._counter--;
if (stat.isDirectory()) {
dir = true;
self.walk.call(self, abspath, callback);
} else
callback.call(self, abspath);
if (false === dir && 0 >= self._counter)
callback.call(self, null);
});
});
});
}
};
new Walker().walk('/home/node', function(file) {
if (null === file)
this.walk( ... ); // Do some more walking
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment