Andrew Andrew - 2 months ago 16
Node.js Question

How to write to a stream after piping?

In NodeJS I have this using ExpressJS (where

res
is a writable stream)

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


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?

Answer

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