Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

nodejs
unshift

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

Sarvech Qadir

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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);

RELATED TAGS

nodejs
unshift

CONTRIBUTOR

Sarvech Qadir
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring