DEV Community

Discussion on: Feb. 14, 2020: What did you learn this week?

Collapse
 
richardeschloss profile image
Richard Schloss • Edited

I learned that in 2020, in NodeJS, the thing to use now for streams is the built-in pipeline. Previously we dealt with streams like this:

res.pipe(outStream) // Pipe an http response to a destination

A few years ago, we were told to use pump, a separate module in npm. But now, pipeline is built into NodeJS and you can just use that!

So, pipelining can now look like this:

pipeline(res, outStream)
.then(handleDone) // .then if you promisified "pipeline"
.catch(handleError)

This way, you can have an array of streams that might be conditionally set:

const streams = [res]
if (res.headers['content-encoding'] === 'gzip') {
  streams.push(createGunzip())
}
streams.push(outStream)

pipeline(...streams) // We can now use the spread syntax with pipeline. 
...

(FYI: it's also a good idea to read about Backpressuring in Node)