0
0
Node.jsframework~5 mins

Stream backpressure concept in Node.js

Choose your learning style9 modes available
Introduction

Backpressure helps control data flow in streams so the receiver is not overwhelmed. It keeps the data moving smoothly without crashes or slowdowns.

When reading large files and writing to a slow destination like a network or disk.
When processing data streams from sensors or user input that can be faster than processing speed.
When piping data between two streams to avoid memory overload.
When building real-time applications that handle continuous data flow.
When you want to keep your app responsive and avoid crashes due to too much data at once.
Syntax
Node.js
const readable = getReadableStream();
const writable = getWritableStream();

readable.on('data', (chunk) => {
  const canWrite = writable.write(chunk);
  if (!canWrite) {
    readable.pause();
    writable.once('drain', () => {
      readable.resume();
    });
  }
});

readable.pause() stops the data flow temporarily.

writable.once('drain') waits for the writable stream to be ready again.

Examples
Basic backpressure handling: pause reading when writable is full, resume when ready.
Node.js
readable.on('data', (chunk) => {
  if (!writable.write(chunk)) {
    readable.pause();
    writable.once('drain', () => readable.resume());
  }
});
Using pipe() automatically manages backpressure for you.
Node.js
readable.pipe(writable);
Sample Program

This program copies a file using streams. It pauses reading when the writable stream is full and resumes when it can accept more data. This prevents memory overload and keeps the process smooth.

Node.js
import { createReadStream, createWriteStream } from 'node:fs';

const readable = createReadStream('input.txt');
const writable = createWriteStream('output.txt');

readable.on('data', (chunk) => {
  const canWrite = writable.write(chunk);
  if (!canWrite) {
    readable.pause();
    writable.once('drain', () => {
      readable.resume();
    });
  }
});

readable.on('end', () => {
  writable.end();
  console.log('Copy complete');
});
OutputSuccess
Important Notes

Backpressure is important to avoid crashes or slowdowns when handling large or fast data streams.

Using pipe() is the easiest way to handle backpressure automatically.

Always listen for the drain event on writable streams to know when to resume reading.

Summary

Backpressure controls data flow between streams to prevent overload.

Pause the readable stream when writable is full, resume on drain.

Use pipe() for automatic backpressure handling.