Skip to main content

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:

  1. Flowing mode Data is read automatically and immediately delivered to data event handlers.
javascript
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'); });
  1. Paused mode The stream waits for you to call .read() manually.
javascript
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

EventDescription
dataFires when a new chunk of data arrives
endThe stream has finished, no more data
errorAn error occurred while reading
closeThe stream is fully closed
readableread() can be called, data is ready

Pipe (redirecting a stream)

One of the most powerful uses is passing data directly into a Writable Stream:

javascript
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 ready
Premium

A concise answer to help you respond confidently on this topic during an interview.