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

We use the readable.unshift() method in Readable streamsstreams or files from which we read data when it is vital to push some chunk of data into the internal buffer. This method is highly useful when the memory is fully used, in order to clear some space by moving the chunks of data to internal buffer.

Syntax:

readable.unshift( chunk, encoding )

Parameters

chunk: The chunk of data that is passed for the execution of the unshift operation.

encoding: The type of encoding. This represents the Buffer encoding, such as ‘utf-8’ or ‘ascii’.

Return value

There is no return value. If you call this method, that executes the functionality of the unshift operation.

Code

Let’s look at the coding example to further understand this method. In this code, we read data from the file and move it to the internal buffer using the .unshift() method.

index.js
input.txt
// fs module for reading writing data
const fs = require('fs');
// readable stream using our declared file.
const readable = fs.createReadStream("input.txt");
// initializing our chunk
let chunk;
readable.on('readable', () => {
// while loop to iterate through the file
while (chunk = readable.read()) {
// Displaying the chunk of data
console.log(`read: ${chunk}`);
}
});
// Calling unshift method to move the chunk to buffer.
readable.unshift(chunk);

Free Resources

Copyright ©2026 Educative, Inc. All rights reserved