Nodejs Fstreampipe道多个文件时触发多个“结束”callback

问题:我试图找出一种方法来将多个文件传输到fstream.Reader时只触发一个“结束”事件。

平台:节点0.6.21

有没有更好的方法来处理这个问题?

var r = fstream.Reader({ path: source, // source is a directory with two files. type: 'File' }).pipe(zlib.createGunzip()).pipe(tar.Extract({ strip: strip, path: destination })); r.on('end', function() { // this is firing everytime a file is extracted. Ideally, I would only fire one 'end' event. if (typeof callback === 'function') { return callback(null); } }); 

结果提取两个文件=两个'结束'callback。 任何意见表示赞赏。 谢谢。

你可以使用其他库吗? Lodash#之后或下划线#之后将在这里帮助。

你可以做类似的事情

 // call `next` twice will call then call `callback` var next = _.after(2, callback); var r = fstream.Reader({ path: source, // source is a directory with two files. type: 'File' }).pipe(zlib.createGunzip()).pipe(tar.Extract({ strip: strip, path: destination })); r.on('end', function() { next(); }); 

或者,使用asynchronous

 function read(p, next) { var r = fstream.Reader({path: p}); // read code like above r.on('end', next); } var tasks = [ read.bind(null, 'path/to/first/file'), read.bind(null, 'path/to/second/file') ]; // callback will be called after all files do `end` .. only once async.parallel(tasks, callback); 

原来这是节点0.6的已知问题。 如果您遇到此问题,您将希望避免使用stream或升级您的节点。