Node.js Stream readable.unshift() Method
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:
const fs = require( 'fs' );
var data = '' ;
const readable = fs.createReadStream( "input.text" );
readable.on( 'readable' , () => {
let chunk;
while ( null !== (chunk = readable.read())) {
console.log(`read: ${chunk}`);
}
});
console.log( "Program ends!!!" );
readable.unshift(data);
|
Output:
Program ends!!!
true
read: GfG
Example 2:
const fs = require( 'fs' );
var data = '' ;
const readable = fs.createReadStream( "input.text" );
readable.setEncoding( 'utf8' );
readable.on( "readable" , () => {
let data = readable.read();
while (data === "GfG" ) {
readable.unshift(data);
data = readable.read();
}
});
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
Share your thoughts in the comments
Please Login to comment...