Node.js Stream.pipeline() Method
Last Updated :
30 Mar, 2023
The stream.pipeline() method is a module method that is used to the pipe by linking the streams passing on errors and accurately cleaning up and providing a callback function when the pipeline is done.
Syntax:
stream.pipeline(...streams, callback)
Parameters: This method accepts two parameters as mentioned above and described below.
- …streams: These are two or more streams that are to be piped together.
- callback: This function is called when the pipeline is fully done and it shows an ‘error’ if the pipeline is not accomplished.
Return Value: It returns a cleanup function.
The below examples illustrate the use of the stream.pipeline() method in Node.js:
Example 1:
Javascript
const fs = require( 'fs' );
const zlib = require( 'zlib' );
const { pipeline } = require( 'stream' );
const { promisify } = require( 'util' );
const pipelineAsync = promisify(pipeline);
const readable = fs.createReadStream( "input.text" );
const writable = fs.createWriteStream( "output.text" );
const transform = zlib.createGzip();
(async function run() {
try {
await pipelineAsync(
readable,
transform,
writable
);
console.log( "pipeline accomplished." );
}
catch (err) {
console.error( 'pipeline failed with error:' , err);
}
})();
|
Output:
Promise { }
pipeline accomplished.
Example 2:
javascript
const fs = require( 'fs' );
const zlib = require( 'zlib' );
const { pipeline } = require( 'stream' );
const { promisify } = require( 'util' );
const pipelineAsync = promisify(pipeline);
const readable = fs.createReadStream( "input.text" );
const writable = fs.createWriteStream( "output.text" );
const transform = zlib.createGzip();
(async function run() {
try {
await pipelineAsync(
readable,
writable,
transform
);
console.log( "pipeline accomplished." );
}
catch (err) {
console.error( 'pipeline failed with error:' , err);
}
})();
|
Output: Here, the order of streams is not proper while piping so an error occurs.
Promise { }
pipeline failed with error: Error [ERR_STREAM_CANNOT_PIPE]: Cannot pipe, not readable
at WriteStream.Writable.pipe (_stream_writable.js:243:24)
at pipe (internal/streams/pipeline.js:57:15)
at Array.reduce ()
at pipeline (internal/streams/pipeline.js:88:18)
at Promise (internal/util.js:274:30)
at new Promise ()
at pipeline (internal/util.js:273:12)
at run (/home/runner/ThirstyTimelyKey/index.js:33:11)
at /home/runner/ThirstyTimelyKey/index.js:45:5
at Script.runInContext (vm.js:133:20)
Reference: https://nodejs.org/api/stream.html#stream_stream_pipeline_streams_callback.
Share your thoughts in the comments
Please Login to comment...