Node.js | stream.Readable.from() Method

The stream.Readable.from() method is an inbuilt application programming interface of the Stream module which is used to construct Readable Streams out of iterators.

Syntax:

stream.Readable.from( iterable, options )

Parameters: This method accept two parameters as mentioned above and described below:

  • iterable: It is an object which implements the Symbol.asyncIterator or Symbol.iterator iterable protocol.
  • options: It is an options provided to the new stream.Readable([options]). By default, the Readable.from() method will set options.objectMode to true, unless its not set to false manually.

Return Value: It returns stream.Readable.

Below examples illustrate the use of stream.Readable.from() method in Node.js:



Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Node.js program to demonstrate the     
// stream.Readable.from() method
  
// Constructing readable from stream
const { Readable } = require('stream');
  
// Using async function
async function * generate() {
  yield 'GfG';
  yield 'CS-Portal...';
}
// Using stream.Readable.from() method
const readable = Readable.from(generate());
  
// Handling data event
readable.on('data', (chunk) => {
  console.log(chunk);
});
console.log("Program completed!!");

chevron_right


Output:

Program completed!!
GfG
CS-Portal...

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Node.js program to demonstrate the     
// stream.Readable.from()
// method
  
// Constructing readable from stream
const { Readable } = require('stream');
  
// Using async function
async function * generate() {
  yield 'Nidhi';
  yield 'GeeksforGeeks';
}
// Using stream.Readable.from() method
const readable = Readable.from(generate());
  
// Handling data event
readable.on('data', (chunk) => {
  console.log(chunk.length);
});
console.log("Program completed!!");

chevron_right


Output:

Program completed!!
5
13

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




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.