What is Stream Module unshift() in Node.js?
We use the readable.unshift() method in
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.
// fs module for reading writing dataconst fs = require('fs');// readable stream using our declared file.const readable = fs.createReadStream("input.txt");// initializing our chunklet chunk;readable.on('readable', () => {// while loop to iterate through the filewhile (chunk = readable.read()) {// Displaying the chunk of dataconsole.log(`read: ${chunk}`);}});// Calling unshift method to move the chunk to buffer.readable.unshift(chunk);
Free Resources