What is a Readable stream?
A Readable Stream in Node.js is one of the stream types, meant for reading data from a source in pieces, rather than all at once. It lets you work with large files or data streams (for example, HTTP requests, sockets, file streams) without loading the entire content into memory.
The core idea
Instead of getting all the data at once, a Readable Stream delivers it in chunks. That makes processing:
- more memory-efficient, especially with large files;
- asynchronous, data is read as it arrives.
Examples of Readable Streams in Node.js
Several built-in objects already implement the Readable Stream interface:
fs.createReadStream(), reading files;http.IncomingMessage, the body of an incoming HTTP request or response;process.stdin, standard input;net.Socket, TCP sockets.
Readable Stream modes
A Readable Stream can run in two modes:
- Flowing mode
Data is read automatically and immediately delivered to
dataevent handlers.
const fs = require('fs');
const stream = fs.createReadStream('file.txt', 'utf8');
stream.on('data', chunk => {
console.log('Got a chunk of data:', chunk);
});
stream.on('end', () => {
console.log('Reading finished');
});- Paused mode
The stream waits for you to call
.read()manually.
const fs = require('fs');
const stream = fs.createReadStream('file.txt', 'utf8');
stream.on('readable', () => {
let chunk;
while ((chunk = stream.read()) !== null) {
console.log('Read a chunk:', chunk);
}
});Important Readable Stream events
| Event | Description |
|---|---|
data | Fires when a new chunk of data arrives |
end | The stream has finished, no more data |
error | An error occurred while reading |
close | The stream is fully closed |
readable | read() can be called, data is ready |
Pipe (redirecting a stream)
One of the most powerful uses is passing data directly into a Writable Stream:
const fs = require('fs');
const readable = fs.createReadStream('input.txt');
const writable = fs.createWriteStream('output.txt');
readable.pipe(writable);
pipe()automatically manages the flow, it reads exactly as much as the other stream can keep up writing.
Advantages of Readable Streams
- Asynchronous (doesn't block the event loop)
- Low memory use
- Chainable (
pipe()) - Supports backpressure (controlling transfer speed)
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.