From a834a070afbbeb0b54a9c6de58e9a0abdd9a3b11 Mon Sep 17 00:00:00 2001 From: AJ ONeal Date: Thu, 3 Feb 2011 15:05:25 -0700 Subject: [PATCH] added EventEmitter to Jorge's Queued example --- lib/walk-jqueue-0.js | 1 + lib/walk-jqueue-1.js | 86 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 87 insertions(+) create mode 120000 lib/walk-jqueue-0.js create mode 100644 lib/walk-jqueue-1.js diff --git a/lib/walk-jqueue-0.js b/lib/walk-jqueue-0.js new file mode 120000 index 0000000..e5352f3 --- /dev/null +++ b/lib/walk-jqueue-0.js @@ -0,0 +1 @@ +walk-jorge.js \ No newline at end of file diff --git a/lib/walk-jqueue-1.js b/lib/walk-jqueue-1.js new file mode 100644 index 0000000..c1ad1de --- /dev/null +++ b/lib/walk-jqueue-1.js @@ -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; +}());