What is Stream Module pipe() in Node.js?

The pipe() method was added in Node version 0.9.4. We use this method to join or pipe two streams together. Basically, this method is called on a readable stream to pass data to write onto a writable stream.

widget

Syntax

pipe(writable_stream, options)

Parameters

  1. writable_stream: This is a required parameter. It is the stream that contains the destination file to write the data into.

  2. options: This is an optional parameter, and it mentions an object to be passed as an optional parameter.

Return Value

Calling pipe() leads to the execution of the pipe() method. The event is emitted and nothing is returned.

Code

Let’s look at an example of transferring data from one file to another.


// Accessing fs module for file reading/writing
const fs = require('fs');
  
// readable stream
const readable = fs.createReadStream("readable_file.txt");
  
// writable Stream
const writable = fs.createWriteStream("writable_file.text");
  
// Calling pipe method to write the content of readable_file into the writable_file. 
readable.pipe(writable);

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved