为什么fs.createReadStream只管道一次?

时间:2015-06-18 11:00:43

标签: node.js

我想管道fs.createReadStream两次,代码在这里:

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)
谁能告诉我原因?

1 个答案:

答案 0 :(得分:3)

您无法将可读流传输到另一个可读流。流程是:

readable.pipe(writable);

可写,在这种情况下,可能是:

因此,如果您尝试读取多个文件并将它们传递给可写流,则必须将每个文件传输到可写流并在执行时传递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