节点stream – 当stream完成时,使同步返回数组。

我写了这个函数从stream中提取文件列表。 它工作,但是stream是asynchronous的, files数组在stream完成之前返回。 我真的不想使用承诺库…尽量保持代码轻。 stream完成后如何返回files数组?

 function fileList(source) { var files = []; source.pipe(through2.obj(function(obj, enc, next) { file = obj.history[0].split("/").pop(); files.push(file); next(); })); return files; } 

提供一个callback,而不是从函数返回一个值:

 function fileList(source, callback) { var files = []; source.pipe(through2.obj(function(obj, enc, next) { file = obj.history[0].split("/").pop(); files.push(file); next(); }, function(flushcb) { flushcb(); callback(null, files); })); } // ... fileList(stream, function(err, files) { if (err) throw err; // use `files` here ... });