我想管道fs.createReadStream两次,代码在这里: fs.createReadStream('pdf-sample1.pdf') .pipe(fs.createWriteStream('pdf-sample2.pdf')) .pipe(fs.createWriteStream('pdf-sample3.pdf')) 但我遇到了一个错误: Error: Cannot pipe.
fs.createReadStream('pdf-sample1.pdf') .pipe(fs.createWriteStream('pdf-sample2.pdf')) .pipe(fs.createWriteStream('pdf-sample3.pdf'))
但我遇到了一个错误:
Error: Cannot pipe. Not readable. at WriteStream.Writable.pipe (_stream_writable.js:162:22) at repl:1:86 at REPLServer.defaultEval (repl.js:132:27) at bound (domain.js:254:14) at REPLServer.runBound [as eval] (domain.js:267:12) at REPLServer.<anonymous> (repl.js:279:12) at REPLServer.emit (events.js:107:17) at REPLServer.Interface._onLine (readline.js:214:10) at REPLServer.Interface._line (readline.js:553:8) at REPLServer.Interface._ttyWrite (readline.js:830:14)
谁能告诉我原因?
您无法将可读流传输到另一个可读流.流程是:readable.pipe(writable);
在这种情况下,可写的可以是:
> a Writable Stream;
> a Duplex Stream;
>或Transform Stream.
因此,如果您尝试读取多个文件并将它们传输到可写流,则必须将每个文件传递给可写流,并在执行时传递end:false,因为默认情况下,可读流结束可写流什么时候没有更多的数据需要阅读.这是一个例子:
var ws = fs.createWriteStream('output.pdf'); fs.createReadStream('pdf-sample1.pdf').pipe(ws, { end: false }); fs.createReadStream('pdf-sample2.pdf').pipe(ws, { end: false }); fs.createReadStream('pdf-sample3.pdf').pipe(ws);
当然,这不是最好的方法,你可以实现一个函数来以更通用的方式包装这个逻辑,可能有一个循环或recursive solution.
更简单的解决方案是使用已解决此问题的模块,如this one here.