Node.js | Stream readable[Symbol.asyncIterator]() Method

The readable[Symbol.asyncIterator]() method in a Readable Stream is utilized to fully consume the stream.

Syntax:

readable[Symbol.asyncIterator]()

Parameters: This method does not accept any parameters.

Return Value: It returns asyncIterator to fully consume the stream.

Below examples illustrate the use of readable[Symbol.asyncIterator]() method in Node.js:



Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Node.js program to demonstrate the     
// readable[Symbol.asyncIterator]()
// method  
  
// Include fs module
const fs = require('fs');
  
// Using async function
async function print(readable) {
  
  // Setting the encoding
  readable.setEncoding('utf8');
  let data = '';
  for await (const chunk of readable) {
    data += chunk;
  }
  console.log(data);
}
print(fs.createReadStream('input.text')).catch(console.error);

chevron_right


Output:

Promise { <Pending> }
GeeksforGeeks

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Node.js program to demonstrate the     
// readable[Symbol.asyncIterator]()
// method  
  
// Constructing readable from stream
const { Readable } = require('stream');
  
// Using async function
async function * generate() {
  yield 'GfG';
  yield 'CS-Portal';
}
  
// Creating readable streams from iterables
const readable = Readable.from(generate());
  
readable.on('data', (chunk) => {
  console.log(chunk);
});
  
console.log("program ends!!!");

chevron_right


Output:

program ends!!!
GfG
CS-Portal

Reference: https://nodejs.org/api/stream.html#stream_readable_symbol_asynciterator.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.