Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

node.js - why fs.createReadStream only pipe one time?

I want pipe 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 meet an 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can't pipe a readable stream to another readable stream. The flow is:

readable.pipe(writable);

A writable, is this case, could be:

So, if you're trying to read multiple files and pipe them to a writable stream, you have to pipe each one to the writable stream and and pass end: false when doing it, because by default, a readable stream ends the writable stream when there's no more data to be 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 could implement a function to wrap this logic in a more generic way, maybe with a loop or a recursive solution.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.5k users

...