Node.js

Copy a stream with pipeline error handling

Use the promise-based pipeline helper to connect readable and writable streams. Await it so completion and stream errors reach normal async control flow.

Worked example

Node.js example · save as example.mjs and run node example.mjs

import * as fs from "node:fs/promises";
import {tmpdir} from "node:os";
import {join} from "node:path";
const directory = await fs.mkdtemp(join(tmpdir(), "file-guide-"));
try {
  const {createReadStream, createWriteStream} = await import("node:fs");
  const {pipeline} = await import("node:stream/promises");
  const source = join(directory, "input.txt");
  const target = join(directory, "output.txt");
  await fs.writeFile(source, "streamed content");
  await pipeline(createReadStream(source), createWriteStream(target));
  console.log(await fs.readFile(target, "utf8"));
} finally {
  await fs.rm(directory, {recursive: true, force: true});
}

How it works

Pipeline connects flow control and propagates failures through the returned promise. The streams can transfer data incrementally rather than allocating the full file as one JavaScript string. The final read is only a small fixture verification.

Limits and mistakes

A failed pipeline may leave a partial destination file. Choose overwrite and cleanup behavior deliberately, especially for valuable outputs. Streaming limits buffering but does not guarantee constant memory if transforms retain all the data they see.

Check the result

Expect streamed content. Test an unreadable source and verify that a failure is reported. For large-file checks, inspect byte counts or hashes rather than reading everything back into memory.

Sources

Reference documentation for the behavior used in this guide: