From f1c2c4d5e1a58ebf146fbe034a3946b37da0c02a Mon Sep 17 00:00:00 2001 From: AJ ONeal Date: Sun, 15 Jan 2012 19:21:11 -0700 Subject: [PATCH] [ISSUE #6] initial 'path' may, in fact, be a file --- lib/walk.js | 62 +++++++++++++++++++++++++++++++++-------------------- 1 file changed, 39 insertions(+), 23 deletions(-) diff --git a/lib/walk.js b/lib/walk.js index abebff6..9ee9927 100644 --- a/lib/walk.js +++ b/lib/walk.js @@ -17,7 +17,9 @@ var emitter = new EventEmitter() , q = [] , queue = [q] - , curpath; + , curpath + , firstRun = true + ; function readdirHandler(err, files) { var fnodeGroups = TypeEmitter.createNodeGroups(); @@ -69,27 +71,45 @@ }); } + function readFiles() { + if (!files || 0 == files.length) { + return next(); + } + + // TODO could allow user to selectively stat + // and don't stat if there are no stat listeners + emitter.emit('names', curpath, files, noop); + + if (sync) { + files.forEach(function (items) { + filesHandler(noop, items); + }); + postFilesHandler(); + } else { + forEachAsync(files, filesHandler).then(postFilesHandler); + } + } + if (err) { - emitter.emit('directoryError', curpath, { error: err }, noop); + if (!firstRun) { + emitter.emit('directoryError', curpath, { error: err }, noop); + readFiles(); + return; + } + + firstRun = false; + fs.lstat(curpath, function (e, stat) { + if (stat) { + files = [curpath.replace(/.*\//, '')]; + curpath = curpath.replace(files[0], ''); + } + readFiles(); + }) //emitter.emit('error', curpath, { error: err }); + return; } - if (!files || 0 == files.length) { - return next(); - } - - // TODO could allow user to selectively stat - // and don't stat if there are no stat listeners - emitter.emit('names', curpath, files, noop); - - if (sync) { - files.forEach(function (items) { - filesHandler(noop, items); - }); - postFilesHandler(); - } else { - forEachAsync(files, filesHandler).then(postFilesHandler); - } + readFiles(); } function walkSync() { @@ -105,11 +125,6 @@ } function walk() { - if (sync) { - walkSync(); - return; - } - fs.readdir(curpath, readdirHandler); } @@ -132,6 +147,7 @@ curpath = pathname; if (sync) { + walk = walkSync; process.nextTick(walk); } else { walk();