Streams

Read chunks

Streams deliver data piece by piece instead of loading the whole file into memory. A readable stream emits a data event for every chunk, which keeps memory flat even for huge files.

Create a read stream from node:fs and listen for data with the on method. Each chunk arrives as it is read from disk, so processing can start before the file ends. The program writes a small file, reads it as a stream and prints the chunk as text.

import { createReadStream, writeFileSync } from "node:fs"; writeFileSync("notes.txt", "hello"); const input = createReadStream("notes.txt"); input.on("data", function (chunk): void { console.log(chunk.toString()); });

hello

Pipe them

Piping connects a readable stream to a writable one with one method call. Data flows chunk by chunk from source to destination without manual buffering.

Create a write stream for the target file and call pipe on the reader. Backpressure and cleanup travel through the pipe, so ten lines replace pages of manual code. The program writes a two-line file, copies it and prints the copy when the writer finishes.

import { createReadStream, createWriteStream, readFileSync, writeFileSync } from "node:fs"; writeFileSync("a.txt", "line one\nline two\n"); const reader = createReadStream("a.txt"); const writer = createWriteStream("b.txt"); reader.pipe(writer); writer.on("finish", function (): void { console.log(readFileSync("b.txt", "utf8").trim()); });

line one
line two

Transform inline

A transform stream sits in the middle of a pipe and rewrites each chunk on the way through. Upper casing text is the classic first example of an inline step.

Build a Transform from node:stream with a small transform function that converts the chunk and passes it to done. Then pipe the reader through it into the writer. The program sends a word through the transform and prints the file that comes out.

import { createReadStream, createWriteStream, readFileSync, writeFileSync } from "node:fs"; import { Transform } from "node:stream"; writeFileSync("a.txt", "hello"); const upper = new Transform({ transform(chunk, _encoding, done): void { done(null, chunk.toString().toUpperCase()); } }); const reader = createReadStream("a.txt"); const writer = createWriteStream("b.txt"); reader.pipe(upper).pipe(writer); writer.on("finish", function (): void { console.log(readFileSync("b.txt", "utf8")); });

HELLO

Respect backpressure

A fast reader can overwhelm a slow writer, so write returns a boolean hint after every call. When it returns false, pause the reader until the writer drains.

Listen once for the drain event and resume the reader inside the handler. This tiny pause and resume loop is the whole secret behind stable pipes. The program copies a file large enough to fill the write buffer and prints the size of the copy.

import { createReadStream, createWriteStream, readFileSync, writeFileSync } from "node:fs"; writeFileSync("big.txt", "x".repeat(200000)); const fast = createReadStream("big.txt"); const slow = createWriteStream("big.copy.txt"); fast.on("data", function (chunk): void { const ok: boolean = slow.write(chunk); if (ok === false) { fast.pause(); slow.once("drain", function (): void { fast.resume(); }); } }); fast.on("end", function (): void { slow.end(function (): void { console.log(readFileSync("big.copy.txt", "utf8").length); }); });

200000

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Why does a stream keep memory flat?

    Answer

    It delivers the data piece by piece instead of the whole file at once

    Only the chunk in flight is held, so a huge file costs the same memory as a small one.

  2. What does pipe connect?

    Answer

    A readable stream to a writable one

    The data flows chunk by chunk, and backpressure and cleanup travel with the pipe.

  3. What does a transform stream do?

    Answer

    It rewrites each chunk on the way through the pipe

    The transform function changes the chunk and passes it on, so it sits in the middle of the chain.

  4. What does write return when the buffer is full?

    Answer

    false, and the reader should pause until drain

    The boolean is the backpressure hint, and the drain event says when the writer is ready again.

  5. What does this program print? import { writeFileSync } from "node:fs"; writeFileSync("note.txt", "abc"); console.log("written");

    Answer

    written

    The file is written before the log line, so the console shows that one line.

  6. What does this program print? import { writeFileSync, readFileSync } from "node:fs"; writeFileSync("a.txt", "line one\nline two\n"); console.log(readFileSync("a.txt", "utf8").trim().split("\n").length);

    Answer

    2

    The trim removes the last newline, and the split leaves two lines.

  7. What does this program print? import { writeFileSync, readFileSync } from "node:fs"; writeFileSync("b.txt", "hello"); console.log(readFileSync("b.txt", "utf8").toUpperCase());

    Answer

    HELLO

    The text is read back and printed in upper case, the same rewrite a transform stream does chunk by chunk.

  8. What does this program print? let total = 0; for (const bytes of [10, 20, 30]) { total += bytes; } console.log(total);

    Answer

    60

    The loop adds the chunk sizes, which is how a program counts what a stream delivered.

  9. What does the compiler say about this program? import { createReadStream } from "node:fs"; const input = createReadStream("notes.txt"); input.on("data", function (chunk: number): void { console.log(chunk); });

    Answer

    error TS2345: Argument of type '(chunk: number) => void' is not assignable to parameter of type '(chunk: string | Buffer<ArrayBufferLike>) => void'.

    The data event hands a buffer or a string, and the declared number parameter matches no overload of on.

  10. What does the compiler say about this program? import { createWriteStream } from "node:fs"; const writer = createWriteStream("b.txt"); const ok: string = writer.write("start"); console.log(ok);

    Answer

    error TS2322: Type 'boolean' is not assignable to type 'string'.

    write gives the backpressure hint as a boolean, and the annotation asks for text.

Article author: Arthur Isaev