节点中的asynchronousrecursionReaddir

我试图用我写的recursion函数来扫描文件和子目录的大目录。 这和这个答案中给出的并行循环非常相似。

var fs = require('fs'); var walk = function(dir, done) { var results = []; fs.readdir(dir, function(err, list) { if (err) return done(err); var pending = list.length; if (!pending) return done(null, results); list.forEach(function(file) { file = dir + '/' + file; fs.stat(file, function(err, stat) { if (stat && stat.isDirectory()) { walk(file, function(err, res) { results = results.concat(res); if (!--pending) done(null, results); }); } else { results.push(file); if (!--pending) done(null, results); } }); }); }); }; 

这个问题是不是真的asynchronous。 整个事情处理并返回一个巨大的数组文件。 有没有办法recursion扫描目录asynchronous?

更像是:

 walk(path,function(files) { // do stuff with each file as its found }); 

编辑:一旦我开始获取文件,我打算访问它们,并使用async模块来处理它们,并防止使用文件描述符。 所以像这样的东西:

 walk(path,function(files) { async.each(files,function() { // do more stuff } }); 

这将工作好与asynchronous扫描?

HeadCode已经在上面的评论中解释了它。 你可以使用eventEmitter来做这种asynchronousrecursion的东西。 对于您的代码,您可以将漫游function作为事件callback。

 var EventEmitter = require("events").EventEmitter; var ee = new EventEmitter(); ee.on("walk", YourWalkFunction); ee.emit("walk",YourParams);