问题:我正在尝试找出一种方法,在将多个文件传输到 fstream.Reader 时仅触发一个“结束”事件。
平台: Node 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);
}
});
提取两个文件时的结果 = 两个“结束”回调。任何建议表示赞赏。谢谢。
最佳答案
你可以使用其他库吗? Lodash#after或Underscore#after在这里会有所帮助。
你可以做类似的事情
// 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();
});
或者,使用async
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);
关于javascript - Nodejs Fstream 在管道传输多个文件时触发多个 'end' 回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22257805/