added EventEmitter to Jorge's Queued example

This commit is contained in:
AJ ONeal 2011-02-03 15:05:25 -07:00
parent edc248289b
commit a834a070af
2 changed files with 87 additions and 0 deletions

1
lib/walk-jqueue-0.js Symbolic link
View File

@ -0,0 +1 @@
walk-jorge.js

86
lib/walk-jqueue-1.js Normal file
View File

@ -0,0 +1,86 @@
(function () {
"use strict"
var fs = require('fs'),
EventEmitter = require('events').EventEmitter;
// 2010-11-25 jorge@jorgechamorro.com
function create (pathname, cb) {
var emitter = new EventEmitter(),
q = [],
queue = [q],
curpath;
function walk() {
//cb(curpath);
fs.lstat(curpath, function (err, stat) {
if (err) {
emitter.emit('error', curpath, err);
}
if (!stat) {
return next();
}
emitter.emit('node', curpath, stat);
if (!stat.isDirectory()) {
return next();
}
fs.readdir(curpath, function(err, files) {
if (err) {
emitter.emit('error', curpath, err);
}
// XXX bug was here. next() was omitted
if (!files || 0 == files.length) {
return next();
}
files.sort(sort);
emitter.emit('nodes', curpath, files);
files.forEach(fullPath);
queue.push(q = files);
next();
});
});
}
function next () {
if (q.length) {
curpath = q.pop();
return walk();
}
if (queue.length -= 1) {
q = queue[queue.length-1];
return next();
}
emitter.emit('end');
}
function getDirectory (enqueue) {
fs.readdir(curpath, function(err, files) {
if (!files) return;
//if (err) throw Error(err);
files.sort(sort);
emitter.emit('nodes', curpath, files);
files.forEach(fullPath);
enqueue(files);
});
}
function fullPath(v,i,o) {
o[i]= [curpath, '/', v].join('');
}
function sort(a,b) {
a= a.toLowerCase();
b= b.toLowerCase();
if (a > b) return -1;
if (a < b) return 1;
else return 0;
}
curpath = pathname;
walk();
return emitter;
}
module.exports = create;
}());