Open In App

Node.js Stream readable.unshift() Method

Improve
Improve
Like Article
Like
Save
Share
Report

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 below.

  • chunk: It contains the chunk of data to unshift onto the read queue.
  • encoding: It holds the encoding type.

Return Value: This method shifts the chunk of data to the internal buffer which can be read-only after calling read method again.

Below examples illustrate the use of readable.unshift() method in Node.js:

Example 1:




// Node.js program to demonstrate the     
// readable.unshift() method  
  
// Including fs module
const fs = require('fs');
  
// Declaring data
var data = '';
  
// Constructing readable stream
const readable = fs.createReadStream("input.text");
  
// Instructions for reading data
readable.on('readable', () => {
  let chunk;
   
  // Using while loop and calling
  // read method
  while (null !== (chunk = readable.read())) {
   
    // Displaying the chunk
    console.log(`read: ${chunk}`);
  }
});
console.log("Program ends!!!");
  
// Calling unshift method
readable.unshift(data);


Output:

Program ends!!!
true
read: GfG

Example 2:




// Node.js program to demonstrate the     
// readable.unshift(chunk[, encoding])
// method  
  
// Include fs module
const fs = require('fs');
var data = '';
  
// Create readable stream
const readable = fs.createReadStream("input.text");
  
// Calling setEncoding method
readable.setEncoding('utf8');
  
// Instructions to unshift data
readable.on("readable", () => {
  let data = readable.read();
    
  while (data === "GfG") {
    
    readable.unshift(data);
    data = readable.read();
  }
  });
  
// Displays that program 
// is unshifted
  console.log("Unshifted!!");


Output:

Unshifted!!

Reference: https://nodejs.org/api/stream.html#stream_readable_unshift_chunk_encoding.



Last Updated : 11 Oct, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads