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:
JavaScript
Output:
JavaScript
Output:
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.
// 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);
Program ends!!! true read: GfGExample 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!!");
Unshifted!!Reference: https://nodejs.org/api/stream.html#stream_readable_unshift_chunk_encoding.