Creating a Readable Stream
You'll learn how to build your own custom readable stream using Node.js's Readable constructor.
What Is a Custom Readable Stream?
When the built-in readable streams (like file streams) don't fit your needs, you can create your own. A custom readable stream is like building your own data fountain — you control what flows out, when it flows, and when it stops.
The Readable constructor from Node.js's stream module lets you define the logic for generating or fetching data on demand.
The Core Pattern
To create a custom readable stream, you extend or instantiate Readable and implement the _read() method. This method is called internally when the stream needs more data:
const { Readable } = require('stream');
const myReadable = new Readable({
read() {
// Push data into the stream
this.push('Hello ');
this.push('from ');
this.push('custom stream!');
// Signal the end of the stream
this.push(null);
}
});
myReadable.on('data', (chunk) => {
console.log(chunk.toString());
});
How It Works
this.push(data): Adds data to the internal buffer, making it available to consumersthis.push(null): Signals that the stream has ended (no more data)- The
read()method is invoked automatically when the stream needs data
Think of it like a vending machine you design: read() is the mechanism that dispenses items, push() is how you load the next item, and push(null) means "sold out."
Key Takeaway: Use the Readable constructor and implement the read() method to create custom readable streams that generate or provide data on demand in Node.js.