CodingNeed.

Production engineering workshop · 45 MIN

Node.js · Stream files with backpressure

A slow consumer must constrain a fast producer.

stream.pipeline connects stages, propagates errors and tears down the pipeline. Unlike buffering the entire file, a streaming transform processes chunks within stream high-water marks. Backpressure is a flow-control mechanism, not a hard memory security boundary. An abort signal allows application shutdown or a cancelled request to stop work. Use exclusive output creation so a failed experiment cannot silently overwrite an existing file.

First reproduce the normal path. Then force a failure at each boundary and inspect what remains true.

Read the example

import {createReadStream,createWriteStream} from "node:fs";
import {pipeline} from "node:stream/promises";
import {createGzip} from "node:zlib";

export async function compress(source,destination,signal) {
  await pipeline(
    createReadStream(source),
    createGzip(),
    createWriteStream(destination,{flags:"wx"}),
    {signal}
  );
}
const [source,destination] = process.argv.slice(2);
if (!source || !destination) {
  console.error("Usage: node compress.mjs INPUT OUTPUT.gz");
  process.exitCode=1;
} else {
  compress(source,destination).catch(error => {
    console.error(error.message); process.exitCode=1;
  });
}
Check the expected output
Review the behavior in the stated project environment.

Your challenge

Save this as compress.mjs and run it on a temporary fixture with node compress.mjs input.txt output.txt.gz. Decompress and compare bytes. Test missing input, existing output, and an aborted large pipeline. Define cleanup for a partially written output before adding this to a service.

Solution cost: O(n) input bytes with compression-dependent CPU cost. time · Stream buffers and compression state rather than the entire file. space

Common trap

Manually listening to data and repeatedly writing without handling backpressure can accumulate an unbounded queue.

Study the project implementation
import {createReadStream,createWriteStream} from "node:fs";
import {pipeline} from "node:stream/promises";
import {createGzip} from "node:zlib";

export async function compress(source,destination,signal) {
  await pipeline(
    createReadStream(source),
    createGzip(),
    createWriteStream(destination,{flags:"wx"}),
    {signal}
  );
}
const [source,destination] = process.argv.slice(2);
if (!source || !destination) {
  console.error("Usage: node compress.mjs INPUT OUTPUT.gz");
  process.exitCode=1;
} else {
  compress(source,destination).catch(error => {
    console.error(error.message); process.exitCode=1;
  });
}

Further reading: Official documentation

Essential cookies keep your account signed in. Optional analytics is not configured on this site. Your choice does not affect access to lessons.

Read the Privacy Policy. You can change this choice in the footer.