The Wayback Machine - https://web.archive.org/web/20241126202945/https://www.geeksforgeeks.org/node-js-stream-pipeline-method/
Open In App

Node.js Stream.pipeline() Method

Last Updated : 30 Mar, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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




// Node.js program to demonstrate the   
// stream.pipeline() method
 
// Including fs and zlib module
const fs = require('fs');
const zlib = require('zlib');
 
// Constructing finished from stream
const { pipeline } = require('stream');
 
// Constructing promisify from
// util
const { promisify } = require('util');
 
// Defining pipelineAsync method
const pipelineAsync = promisify(pipeline);
 
// Constructing readable stream
const readable = fs.createReadStream("input.text");
 
// Constructing writable stream
const writable = fs.createWriteStream("output.text");
 
// Creating transform stream
const transform = zlib.createGzip();
 
// Async function
(async function run() {
    try {
 
        // pipelining three streams
        await pipelineAsync(
            readable,
            transform,
            writable
        );
        console.log("pipeline accomplished.");
    }
 
    // Shows error
    catch (err) {
        console.error('pipeline failed with error:', err);
    }
})();


Output:

Promise {  }
pipeline accomplished.

Example 2: 

javascript




// Node.js program to demonstrate the   
// stream.pipeline() method
 
// Including fs and zlib module
const fs = require('fs');
const zlib = require('zlib');
 
// Constructing finished from stream
const { pipeline } = require('stream');
 
// Constructing promisify from
// util
const { promisify } = require('util');
 
// Defining pipelineAsync method
const pipelineAsync = promisify(pipeline);
 
// Constructing readable stream
const readable = fs.createReadStream("input.text");
 
// Constructing writable stream
const writable = fs.createWriteStream("output.text");
 
// Creating transform stream
const transform = zlib.createGzip();
 
// Async function
(async function run() {
    try {
 
        // pipelining three streams
        await pipelineAsync(
            readable,
            writable,
            transform
        );
        console.log("pipeline accomplished.");
    }
 
    // Shows error
    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.



Previous Article
Next Article

Similar Reads

Underscore.js _.pipeline() Method
The _.pipeline() method takes a list of functions, either as an array or as arguments, and returns a function that takes some value as its argument and runs it through a pipeline of the original functions given in this function. Syntax: _.pipeline( func1, func2,..., funcn ); Parameters: This method accepts a single parameter in the form of n functi
2 min read
Lodash _.pipeline() Method
The Lodash _.pipeline() method takes a list of functions, either as an array or as arguments, and returns a function that takes some value as its argument and runs it through a pipeline of the original functions given in this function. Syntax: _.pipeline( func1, func2,..., funcn ); Parameters: This method accepts a single parameter in the form of n
2 min read
Node.js Stream writable.cork() Method
The writable.cork() method is an inbuilt application programming interface of Stream module which is used to write every data into the buffer memory. When we use stream.uncork() or stream.end() methods then the buffer data will be flushed. Syntax: writable.cork() Parameters: This method does not accept any parameters. Return Value: If this method i
2 min read
Node.js Stream writable.write() Method
The writable.write() method is an inbuilt application programming interface of Stream module which is used to write some data to the Writable stream. The callback function is called once the data has been completely handled. Syntax: writable.write( chunk, encoding, callback) Parameters: This method accepts three parameters as mentioned above and de
2 min read
Node.js Stream writable.end() Method
The writable.end() method is an inbuilt application programming interface of Stream module so that no more data can be written to the Writable anymore. The arguments chunk and encoding are optional which will permit one final new chunk of data to be written instantly before closing the stream. Moreover, the optional callback function is added as a
3 min read
Node.js Stream writable.uncork() Method
The writable.uncork() method is an inbuilt application programming interface of Stream module which is used to flush all the buffered data when stream.cork() method was called. Syntax: writable.uncork() Parameters: This method does not accept any parameters. Return Value: If this method is being called then the data which was being corked is again
2 min read
Node.js Stream writable.setDefaultEncoding() Method
The writable.setDefaultEncoding() method is an inbuilt application programming interface of Stream module which is used to set the default encoding for a Writable stream. Syntax: writable.setDefaultEncoding( encoding ) Parameters: This method accepts single parameter encoding which holds the encoding to be used for the Writable stream. Return Value
2 min read
Node.js Stream readable.pause() Method
The readable.pause() method is an inbuilt application programming interface of Stream module which is used to stop the flowing mode from emitting 'data' events. If any data that becomes accessible will continue to exist in the internal buffer. Syntax: readable.pause() Parameters: This method does not accept any parameters. Return Value: If this met
2 min read
Node.js Stream readable.isPaused() Method
The readable.isPaused() method is an inbuilt application programming interface of Stream module which is used to check the current operating state of the Readable streams. Syntax: readable.isPaused() Parameters: This method does not accept any parameters. Return Value: It returns true if the Readable state is paused otherwise returns false. Below e
1 min read
Node.js Stream readable.destroy() Method
The readable.destroy() method is an inbuilt application programming interface of Stream module which is used to destroy the stream. Syntax: readable.destroy( error ) Parameters: This method accepts single parameter error which is optional and it emits an error while handling error event. Return Value: If this method is used then the stream is destr
2 min read
Node.js Stream readable.read() Method
The readable.read() method is an inbuilt application programming interface of Stream module which is used to read the data out of the internal buffer. It returns data as a buffer object if no encoding is being specified or if the stream is working in object mode. Syntax: readable.read( size ) Parameters: This method accepts single parameter size wh
2 min read
Node.js Stream readable.unpipe() Method
The readable.unpipe() method in a Readable Stream is used to detach a Writable stream which was previously attached while using the stream.pipe() method. Syntax: readable.unpipe( destination ) Parameters: This method accepts single parameter destination which is the destination of writable stream to be detached. Return Value: It returns stream.Writ
1 min read
Node.js Stream transform.destroy() Method
The transform.destroy() method in a Readable Stream is used to destroy the transform stream and also emits an 'error' event optionally. Moreover, the transform stream releases any internal resources after this call is made. Syntax: transform.destroy( error ) Parameters: This method accepts single parameters error which emits an error event optional
2 min read
Node.js Stream readable.setEncoding() Method
The readable.setEncoding() method in a Readable Stream is used to set the encoding of the data read. Syntax: readable.setEncoding( encoding ) Parameters: This method accepts single parameter encoding which holds the encoding type. Return Value: It returns the data in the encoded form. Below examples illustrate the use of readable.setEncoding() meth
1 min read
Node.js Stream readable.unshift() Method
The readable.unshift() method in a Readable Stream is utilized to push a chunk of data back into the internal buffer. However, when a stream is being fully consumed and it needs to be "un-consumed" then this method is helpful. Syntax: readable.unshift( chunk, encoding ) Parameters: This method accept two parameters as mentioned above and described
2 min read
Node.js Stream readable[Symbol.asyncIterator]() Method
The readable[Symbol.asyncIterator]() method in a Readable Stream is utilized to fully consume the stream. Syntax: readable[Symbol.asyncIterator]() Parameters: This method does not accept any parameters. Return Value: It returns asyncIterator to fully consume the stream. Below examples illustrate the use of readable[Symbol.asyncIterator]() method in
1 min read
Node.js stream.finished() Method
The stream.finished() method is utilized to receive an alert if a stream is not writable or readable anymore or if it had experienced an error or a close event that is immature. Syntax: stream.finished(stream, options, callback) Parameters: This method accepts three parameters as mentioned above and described below: stream: This parameter can be re
3 min read
Node.js stream.Readable.from() Method
The stream.Readable.from() method is an inbuilt application programming interface of the Stream module which is used to construct Readable Streams out of iterators. Syntax: stream.Readable.from( iterable, options ) Parameters: This method accept two parameters as mentioned above and described below: iterable: It is an object which implements the Sy
2 min read
Node.js Stream writable._write() Method
The writable._write() method is an inbuilt application programming interface of Stream module which is used to implement a writable stream. The writable._write() method is affixed with an underscore as it is inside the class that defines it. Moreover, the user program must not call it directly. This method implemented by using child classes and it
3 min read
Node.js Http2ServerRequest.stream Method
The Http2ServerRequest.stream is an inbuilt application programming interface of class Http2ServerRequest within the http2 module which is used to get the Http2Stream object backing the request. Syntax: const request.stream Parameters: This method does not accept any argument as a parameter. Return Value: This method returns the Http2Stream object
3 min read
Node.js Http2ServerResponse.stream Method
The Http2ServerResponse.stream is an inbuilt application programming interface of class Http2ServerResponse within http2 module which is used to get the object of HTTP stream backing this response. Syntax: response.streamParameters: This method does not accept any arguments as a parameter. Return Value: This method returns an object of HTTP stream
3 min read
Node.js Stream readable.resume() Method
Node.js streams are powerful tools for handling data transfer efficiently, especially when dealing with large datasets or real-time data. The readable.resume() method is a part of the readable stream interface, playing a crucial role in managing the flow of data. This article will delve into what readable.resume() does, how it works, and when to us
4 min read
Node.js Stream readable.pipe() Method
The readable.pipe() method in a Readable Stream is used to attach a Writable stream to the readable stream so that it consequently switches into flowing mode and then pushes all the data that it has to the attached Writable. Syntax:readable.pipe( destination, options )Parameters: This method accepts two parameters as mentioned above and described b
2 min read
Node.js Stream writable.destroy() Method
The writable.destroy() method is an inbuilt application programming interface of Stream module which is used to destroy the created stream and you cannot call the write() method to write data again after you have already destroyed the created stream. Syntax: writable.destroy()Parameters: This method does not accept any parameters. Return Value: It
2 min read
Mongoose Aggregate.prototype.pipeline() API
The Aggregate API.prototype.pipeline() method of the Mongoose API is used to perform aggregation tasks. It allows us to get the current pipeline operation object in the form of an array. It is useful to get all the current pipelining operations or pipeline methods we have applied to perform aggregation tasks. Syntax: aggregate().project( specificat
2 min read
How to Set Up a CI Pipeline for Ktor Using GitHub Actions?
In this article, we'll look at how to use GitHub Actions to create a robust and effective Continuous Integration (CI) pipeline for Ktor applications. Developers have a great foundation to construct high-performance server-side apps thanks to Ktor, a versatile and lightweight Kotlin framework for building web applications. We can automate the build,
6 min read
JavaScript Pipeline Operator
The JavaScript Pipeline Operator (|>) is used for passing the result of one expression into a function. It's particularly useful for making long chains of functions easier to read. With this operator, the value before it gets sent as input to the function that follows. You simply arrange the functions in the order you want them to act on the inp
2 min read
Node.js Stream writable.writableFinished Property
The writable.writableFinished property is set to true instantly before the emit of the 'finish' event. Syntax: writable.writableFinished Return Value: It returns true if 'finish' event is called before it else it returns false. Below examples illustrate the use of writable.writableFinished property in Node.js: Example 1: // Node.js program to demon
2 min read
Node.js Stream writable.writableObjectMode Property
The writable.writableObjectMode property in Stream module is used to get the object mode value of the Writable stream. Syntax: writable.writableObjectMode Return Value: It returns true if the objectMode is set to true otherwise returns false. Below examples illustrate the use of writable.writableObjectMode property in Node.js: Example 1: // Node.js
2 min read
Node.js Stream writable.writableLength Property
The writable.writableLength property is an inbuilt application of stream module which is used to check the number of bytes in the queue that is ready to be written. Syntax: writable.writableLength Return Value: This property returns the number of bytes that is ready to write into the queue. Below examples illustrate the use of writable.writableLeng
2 min read
three90RightbarBannerImg