Course contentsShow
← Node.js
Lesson 402 of 1,9805. Streams and BackpressureFree lesson

The Drain Event Explained

Coordinate data resumption by listening for the signal that a writable stream has flushed its internal buffer.

The Drain Event Explained

In this lesson, you will learn how to safely resume data flow when a writable stream’s internal buffer is finally empty.

When you write data to a stream, Node.js holds that data in a temporary memory buffer. If you write faster than the destination can process it, that buffer fills up. Eventually, the stream hits its "High Water Mark," and the .write() method returns false. This is your signal to stop sending data; continuing to write while the buffer is full risks memory bloat and performance degradation.

This is where the drain event comes in.

Waiting for the Signal

Think of the drain event as a "green light." When the stream has finished processing the data currently in its buffer and is ready for more, it emits the drain event. Until you hear this signal, your code should remain paused to prevent overwhelming the stream.

Here is how you coordinate this:

function writeData(writable, data) {
  if (!writable.write(data)) {
    // The buffer is full. Stop writing and wait for the 'drain' event.
    writable.once('drain', () => {
      console.log('Buffer cleared, resuming writes...');
      // Logic to continue or trigger the next chunk
    });
  } else {
    // The buffer has capacity; keep writing immediately.
  }
}

Why it Matters

By listening for drain, you implement a "pull" mechanism rather than a "push" mechanism. You aren't forcing data into the system; you are waiting for the system to tell you it has the space to accept more. This cycle of writing until false and resuming on drain is the standard way to handle backpressure manually in Node.js. It ensures your application stays performant, avoids memory crashes, and keeps data throughput stable, even when the data source is significantly faster than the destination.

Key Takeaway: Always listen for the drain event when .write() returns false to coordinate data resumption and respect the stream’s buffer capacity.