I found two different ways to pipe streams in node.js
Well known .pipe()
method of a stream
https://nodejs.org/api/stream.html#stream_readable_pip
According to the documentation, they both do the same thing. But there some differences:
.pipe()
is a method of Readable
, while pipeline
is a module method of stream
that accepts streams to pipe.pipeline()
method provide a callback when the pipeline is complete.pipeline()
method was added since 10 version of node, while .pipe
exist from the earliest versions of Node. In my opinion, with pipeline()
code looks a bit cleaner, but you can use both of them.
Example of .pipe()
:
const fs = require('fs');
const r = fs.createReadStream('file.txt');
const z = zlib.createGzip();
const w = fs.createWriteStream('file.txt.gz');
r.pipe(z).pipe(w);
Example of pipeline()
:
const { pipeline } = require('stream');
const fs = require('fs');
const zlib = require('zlib');
pipeline(
fs.createReadStream('archive.tar'),
zlib.createGzip(),
fs.createWriteStream('archive.tar.gz'),
(err) => {
if (err) {
console.error('Pipeline failed.', err);
} else {
console.log('Pipeline succeeded.');
}
}
);