TL;DR - You better want to use pipeline
What's pipeline?
From the docs: A module method to pipe between streams forwarding errors and properly cleaning up and provide a callback when the pipeline is complete.
What's the motivation for using pipeline?
❌
Let's take a look at the following code:
const { createReadStream } = require('fs');
const { createServer } = require('http');
const server = createServer(
(req, res) => {
createReadStream(__filename).pipe(res);
}
);
server.listen(3000);
What's wrong here?
If the response will quit or the client closes the connection - then the read stream is not closed or destroyed, which leads to a memory leak.
✅So if you use pipeline
, it would close all other streams and make sure that there are no memory leaks.
const { createReadStream } = require('fs');
const { createServer } = require('http');
const { pipeline } = require('stream');
const server = createServer(
(req, res) => {
pipeline(
createReadStream(__filename),
res,
err => {
if (err)
console.error('Pipeline failed.', err);
else
console.log('Pipeline succeeded.');
}
);
}
);
server.listen(3000);
res
. So you can't send back a500
status since whencreateReadStream
closes, it will closeres
as well. Then it calls the callback. That doesn't mean it's "bad". Just beware. – Assimilative