将多个文件通过管道传输到单个流 [英] pipe multipe files to a single stream
问题描述
所以我有一个文件名数组.
so i have an array of filenames.
我需要遍历每一个,将其作为一个流读取,一个接一个地通过管道传输到最后一个流.
I need to go through each of those, read it as a stream, pipe one by one to a final stream.
错误地,代码看起来像这样:
Erroneously, the code would look something like this:
var files = ['file1.txt', 'file2.txt', 'file3.txt'];
var finalStream = fs.createReadStream()//throws(i need a file path here)
(function pipeSingleFile(file){
var stream = fs.createReadStream(file);
stream.on('end', function(){
if(files.length > 0){
pipeSingleFile( files.shift() );
}
});
stream.pipe(finalStream);
})( files.shift() )
finalStream.pipe(someOtherStream);
finalStream.on('end', function(){
//all the contents were piped to outside
});
有没有办法做到这一点?
Is there anyway to achieve this?
推荐答案
我没有测试您提出的递归解决方案,但它可能不起作用,因为您正在修改原始 files
数组(在每次迭代中调用 files.shift()
) 两次:在将其传递给您的函数时以及在函数内部时.这是我的建议:
I didn't test the recursive solution you proposed, but it may not work since you're modifying the original files
array (calling files.shift()
) two times on each iteration: when passing it to your function and also inside. Here's my suggestion:
var files = ['file1.txt', 'file2.txt', 'file3.txt'];
var writableStream = fs.createWriteStream('output.txt');
function pipeNext (files, destination) {
if (files.length === 0) {
destination.end();
console.log('Done!');
} else {
var file = files.shift();
var origin = fs.createReadStream(file);
origin.once('end', function () {
pipeNext(files, destination);
});
origin.pipe(destination, { end: false });
console.log('piping file ' + file);
}
}
pipeNext(files, writableStream);
我在文件上使用了 Writable
流作为示例,但您可以使用任何您想要的.您可以将此逻辑包装到另一个函数中,并将您的 Writable
流传递给它.
I used a Writable
stream on a file just as an example, but you could use whatever you want. You can wrap this logic into another function and pass your Writable
stream to it.
这篇关于将多个文件通过管道传输到单个流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!