Why does fs.createReadStream only work once?

I want the string fs.createReadStream

twice, the code is here:

fs.createReadStream('pdf-sample1.pdf')
  .pipe(fs.createWriteStream('pdf-sample2.pdf'))
  .pipe(fs.createWriteStream('pdf-sample3.pdf'))

      

But I am meeting the error:

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)

      

who can tell me the reason?

+3


source to share


1 answer


You cannot pipe the stream being read to another readable stream. Flow:

readable.pipe(writable);

      

Writable, in this case, could be:



So, if you are trying to read multiple files and put them on a writable stream, you need to associate them with the stream being written and piped end: false

when it executes, because by default a readable stream ends up with a writable stream when there is no more data to read. Here's an example:

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);

      

Of course this is not the best way to do it, you can implement a function to wrap this logic in a more general way, perhaps with a loop or a recursive solution .

An even simpler solution would be to use a module that has already solved this problem, such as this one here .

+2


source







All Articles