Search⌘ K
AI Features

Readable Streams: Simplified Construction and Iterables

Explore how to build custom readable streams in Node.js using a simplified constructor that reduces complexity. Understand how to convert arrays and other iterable objects into streams with Readable.from, and learn efficient memory management by leveraging lazy iterables such as generators and async iterators.

Simplified construction

For simple custom streams, we can avoid creating a custom class by using the Readable stream’s simplified construction approach. With this approach, we only need to invoke new Readable(options) and pass a method named read() in the set of options. The read() method here has exactly the same semantic as the _read() method that we saw in the class extension approach. Let's rewrite our RandomStream using the simplified constructor approach.

Node.js
import { Readable } from 'stream'
import Chance from 'chance'
const chance = new Chance()
let emittedBytes = 0
const randomStream = new Readable({
read (size) {
const chunk = chance.string({ length: size })
this.push(chunk, 'utf8')
emittedBytes += chunk.length
if (chance.bool({ likelihood: 5 })) {
this.push(null)
}
}
})
randomStream
.on('data', (chunk) => {
console.log(`Chunk received (${chunk.length} bytes): ${chunk.toString()}`)
})
.on('end', () => {
console.log(`Produced ${emittedBytes} bytes of random data`)
})

This ...