Andrew Andrew - 25 days ago 7
Node.js Question

How to write to a stream after piping?

In NodeJS I have this using ExpressJS (where

is a writable stream)

const readableStream = someAsyncTask();
readableStrean.on('end', () => {
res.write('a bit more');

This is resulting in:

uncaught exception Error: write after end

So I assume the pipe is causing the writable stream to close. How can I pipe the readable stream to the output, and then when that stream ends, stream additional data to the output?


From the documentation

readable.pipe(destination[, options])

  • destination <stream.Writable> The destination for writing data
  • options <Object> Pipe options
    end <Boolean> End the writer when the reader ends. Defaults to true.

If you don't want it to end when piping, pass {end : false} as options

readableStream.pipe(res, { end: false });