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

The 'drain' Event

Resuming writes after backpressure is relieved using the 'drain' event.

The 'drain' Event

What You'll Learn

You'll learn how to use the 'drain' event to safely resume writing to a stream after backpressure has been relieved.

Understanding the 'drain' Event

When you write data to a writable stream, sometimes write() returns false, signaling backpressure—the stream's internal buffer is full and can't accept more data right now. If you keep writing anyway, you risk overwhelming memory.

The 'drain' event is your signal that the coast is clear. It fires when the stream's buffer has emptied enough to accept more writes. Think of it like a traffic light turning green after being red: you were told to wait (write() returned false), and now the 'drain' event tells you it's safe to proceed.

How It Works

Here's the pattern:

const fs = require('fs');
const writable = fs.createWriteStream('output.txt');

function writeData() {
  let canContinue = true;
  let i = 0;

  while (i < 1000000 && canContinue) {
    canContinue = writable.write(`Line ${i}\n`);
    i++;
  }

  if (!canContinue) {
    // Backpressure detected! Wait for 'drain'
    writable.once('drain', () => {
      console.log('Buffer drained, resuming writes');
      writeData(); // Resume writing
    });
  }
}

writeData();

When write() returns false, we stop immediately and register a listener for the 'drain' event. Once the buffer clears, the event fires and we resume writing. This prevents memory buildup and keeps your application efficient.

Key Takeaway

The 'drain' event signals that a writable stream is ready to accept more data after backpressure; always listen for it when write() returns false to safely resume your writes.