Course contentsShow
← JavaScript
Lesson 1552 of 2,72334. Streams and BuffersFree lesson

Reading Data from Readable Streams

Consuming readable streams with the 'data' event and the flowing mode.

Reading Data from Readable Streams

You'll learn how to consume data from a readable stream using the 'data' event in flowing mode.

When you create a readable stream, it doesn't automatically push data into your program—you need to actively consume it. The most straightforward way is to use the 'data' event, which puts the stream into flowing mode.

How Flowing Mode Works

In flowing mode, the stream automatically reads chunks from its source and emits them as fast as possible. Think of it like opening a faucet: once you turn it on (by attaching a 'data' listener), water flows continuously until the source runs dry.

When you attach a listener to the 'data' event, the stream begins emitting chunks of data. Each time a chunk is available, your callback function receives it. When the stream finishes, it emits an 'end' event.

const fs = require('fs');

// Create a readable stream
const readStream = fs.createReadStream('example.txt', { encoding: 'utf8' });

// Listen for 'data' events (this triggers flowing mode)
readStream.on('data', (chunk) => {
  console.log('Received chunk:', chunk);
});

// Listen for 'end' event when stream finishes
readStream.on('end', () => {
  console.log('Stream finished');
});

// Handle errors
readStream.on('error', (err) => {
  console.error('Stream error:', err);
});

The moment you attach the 'data' listener, the stream starts reading and emitting chunks. You don't control the pace—it flows as fast as the source allows. Each chunk is a Buffer (or string if you specified encoding).

Key Takeaway: Attaching a 'data' event listener activates flowing mode, causing the readable stream to automatically emit chunks of data until the source is exhausted or an error occurs.