At 02:00 every night, TinyTickets imported a CSV file of shows from a ticket partner. The file had grown to two million rows. One night the import used so much memory that the server restarted, and buyers saw errors for four minutes.
“Make the import safe for any size of file,” Leo wrote to Maya.
Maya, Leo and TinyTickets are invented, and so are the numbers in their story.
The import reads the whole file into memory before it saves the first show. This module rebuilds it so it reads one row at a time and passes each row through small steps. It does that in three pattern cards, called Card 1 to Card 3, and ends with a short entry on Pipes and Filters.
After this module, you can:
- read a file of any size one line at a time with an async generator and
for await(Card 1) - cut the import into small steps with Node.js streams, and test each step with no file on disk (Card 2)
- join the steps with
pipeline, so one error reaches onecatch, a slow step slows the others, and a signal can stop them all (Card 3) - tell when a plain array is enough
Set up the folder and the shared show code
Use the folder from Module 1, with the same package.json and tsconfig.json. This module needs no new package, because everything comes from Node.js itself.
The import saves shows through a repository, the object from Module 7 that hides how data is stored. Here it has one method, and the fake one prints a line instead of calling a real database. Save this as shows.ts:
// Shared code for Module 8: the Show type, a line parser,
// a fake repository that prints, and a small test file.
export interface Show {
id: string;
title: string;
date: string;
priceCents: number;
}
// The Repository from Module 7, cut down to the one method the import needs
export interface ShowRepository {
save(show: Show): Promise<void>;
}
// shortcut: no quoted fields, so a title cannot hold a comma; use csv-parse when it must
export function parseShow(line: string): Show | null {
const [id, title, date, price, ...extra] = line.split(",");
const priceCents = Number(price);
if (!id || !title || !date || !price || extra.length > 0) return null;
if (!Number.isInteger(priceCents)) return null;
return { id, title, date, priceCents };
}
export function toCsvLine(show: Show): string {
return `${show.id},${show.title},${show.date},${show.priceCents}\n`;
}
export function makeShowRepository(): ShowRepository {
return {
async save(show) {
console.log(`[db] saved ${show.id}`);
},
};
}
export const sampleCsv = [
"id,title,date,priceCents",
"spring,Songs of Spring,2027-03-14,1200",
"broken line",
"summer,Summer Lights,2027-06-20,1500",
].join("\n") + "\n";
parseShow returns null for a line it cannot read, so the import can skip it. sampleCsv is the test file. Each example writes it to disk first, so every example runs on its own.
Maya’s import reads the whole file at once
Here is the nightly import as it runs today. Save it as import-before.ts:
import { readFile, writeFile } from "node:fs/promises";
import { makeShowRepository, parseShow, sampleCsv } from "./shows.ts";
async function importShows(path: string): Promise<void> {
const repo = makeShowRepository();
const text = await readFile(path, "utf8"); // the whole file, as one string
const lines = text.split("\n"); // a second copy, as an array of lines
for (const line of lines.slice(1)) {
if (line === "") continue;
const show = parseShow(line);
if (show === null) {
console.log(`[import] skipped "${line}"`);
continue;
}
await repo.save(show);
}
console.log("[import] done");
}
await writeFile("shows.csv", sampleCsv); // test data for this example
await importShows("shows.csv");
Output of npx tsx import-before.ts:
[db] saved spring
[import] skipped "broken line"
[db] saved summer
[import] done
On four lines this is fine. But look at what the code holds in memory when the file has two million rows. text is the whole file, and lines is a second copy, cut into two million strings. Then lines.slice(1) makes a third array.
All of it stays alive until the loop ends, so the memory the import needs grows with the size of the file. A large enough file also hits a limit on string length, and then readFile throws. “Going deeper” at the end of this module gives the number.
Figure 1 shows what the function holds. It also repeats the legend used in every figure of this course.
+------------------------------------+
(Partner) --> | shows.csv on disk, 2 million rows |
+------------------------------------+
| readFile: every byte, at once
v
+------------------------------------+
| [importShows] |
| text = the whole file | ==> [makeShowRepository]
| lines = a second copy |
| saves start after the last byte |
+------------------------------------+
Legend, the same in every module
(Name) a person
[name] a module, function or class
[name] (I) an interface: a shape that other code must fit
A --> B A calls B
A ..> B A implements B: A has the shape that interface B asks for
A ==> B A creates B (with "new" or a factory function)
NEW a part that the change added
~ await ~ the caller waits here; Node.js serves other work meanwhile
Figure 1: the import holds the whole file twice before it saves the first show.
The function has two more problems that later changes will hit. It creates its own repository, so a test cannot pass in a fake (Module 1, Figure 2). And the loop walks an array built from a file, so it cannot read shows from anywhere else.
Iterator and async iterators
The pain: a loop that needs the whole array first
Leo’s change request was short. The import had to work for a file of any size. Maya’s first idea was to read the file in parts.
But the for loop in importShows walks an array. It cannot start until text.split("\n") has built that array, and the split cannot start until readFile has read every byte. So the way the data is fetched and the way it is used sit in one function.
Pause and predict: the loop body (parse, skip, save) does not care where a line came from. What would the loop need from its data source, at a minimum, to work one line at a time? Write your answer before you read on.
The idea: ask for the next item, one at a time
The Iterator pattern comes from the GoF book that earlier modules used. An iterator gives you the items of a collection one at a time, and hides how the collection is stored. The code that uses the items only asks for the next one, and the iterator knows how to get it.
Think of a box office cashier who calls “next, please”. The cashier serves one buyer at a time and does not care how long the queue is. But a real queue exists before the cashier calls, while an iterator often fetches the next item only when it is asked.
JavaScript builds Iterator into the language through the iteration protocols. An async iterable is any object with a [Symbol.asyncIterator]() method. That method returns an object whose next() method returns a promise of { value, done }. The loop for await (const x of y) calls next() for you and waits for each promise.
So an iterator lets you change where the items come from, and how they are fetched, without touching the code that uses them.
The fix: a generator that reads lines, a loop that uses them
The shortest way to write an async iterable is an async generator, a function declared with async function*. Each yield hands one value to the loop and pauses the function until the loop asks again.
Node.js already has an iterator for lines. readline.createInterface reads a file stream and gives back an object you can use in for await, one line per step. The option crlfDelay: Infinity makes it treat a Windows line end (\r\n) as one line break. Save import-shows.ts:
import { createReadStream } from "node:fs";
import { createInterface } from "node:readline";
import { parseShow, type ShowRepository } from "./shows.ts";
// The iterator: hands out one data line at a time, skipping the header
export async function* readShowLines(path: string): AsyncGenerator<string> {
const lines = createInterface({ input: createReadStream(path), crlfDelay: Infinity });
let first = true;
for await (const line of lines) {
if (first) {
first = false;
continue;
}
yield line;
}
}
// The consumer: works with any async iterable of lines
export async function importShows(
lines: AsyncIterable<string>,
repo: ShowRepository,
): Promise<void> {
for await (const line of lines) {
if (line === "") continue;
const show = parseShow(line);
if (show === null) {
console.log(`[import] skipped "${line}"`);
continue;
}
await repo.save(show);
}
console.log("[import] done");
}
And run-import.ts, which creates the real parts:
import { writeFile } from "node:fs/promises";
import { importShows, readShowLines } from "./import-shows.ts";
import { makeShowRepository, sampleCsv } from "./shows.ts";
await writeFile("shows.csv", sampleCsv); // test data for this example
await importShows(readShowLines("shows.csv"), makeShowRepository());
npx tsx run-import.ts prints the same four lines as import-before.ts. The difference is in memory. createReadStream reads the file in chunks, pieces of 64 KiB by default.
Readline keeps only the current chunk and the part of a line that is not finished yet. So memory now depends on the longest line, not on the size of the file. The first show is saved after the first chunk arrives, not after the last.
importShows now asks for AsyncIterable<string>, the built-in TypeScript type for anything you can use in for await. It no longer creates the repository either, because the caller passes it in. Figure 2 shows the structure before and after.
Before
[importShows] --> [readFile] whole file
[importShows] ==> [makeShowRepository]
After
[run-import.ts] ==> [readShowLines] NEW
[readShowLines] ..> [AsyncIterable<string>] (I)
[readShowLines] --> [readline] --> [createReadStream] NEW
[run-import.ts] --> [importShows] --> [AsyncIterable<string>] (I)
[run-import.ts] ==> [makeShowRepository]
Figure 2: importShows now depends on “something that gives lines”; the file reading moved into readShowLines.
Figure 3 follows one line through the loop. Each next() is a promise, and the file is read only when a line is needed.
1 [importShows] --> [readShowLines] next()
2 [readShowLines] --> [readline] next()
~ await: readline has no full line yet ~
3 [readline] --> [createReadStream] read the next 64 KiB chunk
~ await: the disk read; Node.js serves buyers meanwhile ~
4 [readline] returns "spring,Songs of Spring,..." to [readShowLines]
5 [readShowLines] yields the line to [importShows], and pauses
6 [importShows] --> [repo] save(spring)
~ await ~
7 [importShows] --> [readShowLines] next() again, back to step 2
Figure 3: one line at a time, and the file is read only when the loop asks for more.
Step 5 is the part that saves memory. The generator pauses after yield, so it reads nothing more while the save in step 6 waits. That means a slow database slows down the file reading too. Card 3 gives this effect a name.
Prove it with a test
The “before” version could only be tested with a real file and the real repository. Now a test can pass a generator of two lines and a fake repository. TypeScript checks shapes (Module 1), so a plain object with a save method fits ShowRepository. Save import-shows.test.ts:
import { test } from "node:test";
import assert from "node:assert/strict";
import { importShows } from "./import-shows.ts";
import type { Show, ShowRepository } from "./shows.ts";
test("importShows saves good lines and skips bad ones", async () => {
const saved: Show[] = [];
const fakeRepo: ShowRepository = {
async save(show) {
saved.push(show);
},
};
async function* fakeLines(): AsyncGenerator<string> {
yield "spring,Songs of Spring,2027-03-14,1200";
yield "broken line";
}
await importShows(fakeLines(), fakeRepo);
assert.deepEqual(saved, [
{ id: "spring", title: "Songs of Spring", date: "2027-03-14", priceCents: 1200 },
]);
});
Run it with npx tsx --test import-shows.test.ts:
[import] skipped "broken line"
[import] done
✔ importShows saves good lines and skips bad ones (1.051791ms)
ℹ tests 1
ℹ pass 1
ℹ fail 0
The two [import] lines are the function’s own output. The test needs no file, no folder and no mocking library.
The next change: a partner API that returns pages
A second ticket partner offered its shows through an HTTP API instead of a file. The API returns a page of CSV lines and the number of the next page. In this module the API is a fake that prints instead of calling a real service. Save partner-import.ts:
import { importShows } from "./import-shows.ts";
import { makeShowRepository } from "./shows.ts";
type Page = { lines: string[]; nextPage: number | null };
// The partner's API, faked: two pages of CSV lines
async function fetchPartnerPage(page: number): Promise<Page> {
console.log(`[partner] page ${page}`);
if (page === 1) return { lines: ["spring,Songs of Spring,2027-03-14,1200"], nextPage: 2 };
return { lines: ["broken line", "summer,Summer Lights,2027-06-20,1500"], nextPage: null };
}
// NEW: a second iterator; it asks for the next page only when the loop needs it
async function* readPartnerLines(): AsyncGenerator<string> {
let page: number | null = 1;
while (page !== null) {
const result = await fetchPartnerPage(page);
yield* result.lines;
page = result.nextPage;
}
}
await importShows(readPartnerLines(), makeShowRepository());
Output:
[partner] page 1
[db] saved spring
[partner] page 2
[import] skipped "broken line"
[db] saved summer
[import] done
yield* hands on every item of another iterable, one at a time, so yield* result.lines yields each line of the page in turn. Page 2 is fetched only after the spring show is saved. importShows did not change at all, because the new source is one new generator.
Use it when, skip it when
Use an async iterator when:
- the data is large or has no end, such as a big file, a paged API or a message queue
- the code that uses items should not know where they come from, and you want to test it with a few fake items
- items arrive over time, and you want to start work on the first one before the last one exists
Skip it when the data is small and already in memory. A list of 40 shows from one database query is an array, and for (const show of shows) is the simpler option. An async generator around an array only adds an await to every step.
The cost
Each next() is a promise and an extra wait, so a loop over a million items does a million small awaits. A generator also hides control flow. When importShows throws, the stack trace shows generator and readline frames between your loop and the file. And an iterator you write as a class must clean up after itself when a loop leaves early, which “Going deeper” explains.
Seen in the wild
- Node.js readline:
rl[Symbol.asyncIterator]()is the iteratorreadShowLinesuses. - Node.js streams: every Readable stream is an async iterable (
readable[Symbol.asyncIterator]()). The next card uses this. - Node.js events:
events.on(emitter, name)returns an async iterator over the events an emitter sends (Module 5).
Often confused with
- Observer (Module 5): the source pushes each item to listeners when it wants. With an iterator, the loop that uses the items pulls the next one when it is ready.
- A Readable stream (next card): also an async iterable, but it reads ahead and connects to other streams.
Exercise: a dry run that stops early
Leo wants a dry run that imports only the first line of the file. Write an async generator firstLines(lines, n) that passes on the first n lines of any async iterable and then stops. importShows must not change.
Answer
Save first-lines.ts:
import { writeFile } from "node:fs/promises";
import { importShows, readShowLines } from "./import-shows.ts";
import { makeShowRepository, sampleCsv } from "./shows.ts";
// A dry run: pass on only the first n lines, then stop
async function* firstLines(lines: AsyncIterable<string>, n: number): AsyncGenerator<string> {
if (n <= 0) return;
let count = 0;
for await (const line of lines) {
yield line;
count++;
if (count === n) return; // leaving the loop stops the file reader too
}
}
await writeFile("shows.csv", sampleCsv);
await importShows(firstLines(readShowLines("shows.csv"), 1), makeShowRepository());
Output:
[db] saved spring
[import] done
firstLines wraps one iterator in another, the way withLogging wrapped a function in Module 1. Its return leaves the inner for await loop, and that closes readShowLines and its readline. So the rest of the file is never read.
Readable and Transform streams
The pain: one more output, written by hand
The partner liked the import. Then Leo asked for a cleaned copy of each night’s file, to send back to organizers. The copy had to hold only the valid shows, gzip-compressed, as shows-clean.csv.gz. Gzip is a common compression format, and Node.js writes it with createGzip() from node:zlib.
Maya added the archive to importShows. Save archive-before.ts:
import { createWriteStream } from "node:fs";
import { readFile, writeFile } from "node:fs/promises";
import { createGzip, gunzipSync } from "node:zlib";
import { readShowLines } from "./import-shows.ts";
import { makeShowRepository, parseShow, sampleCsv, toCsvLine } from "./shows.ts";
import type { ShowRepository } from "./shows.ts";
async function importShows(
lines: AsyncIterable<string>,
repo: ShowRepository,
archivePath: string, // NEW: the import now knows about files again
): Promise<void> {
const gzip = createGzip(); // NEW
const file = createWriteStream(archivePath); // NEW
gzip.pipe(file); // NEW
for await (const line of lines) {
if (line === "") continue;
const show = parseShow(line);
if (show === null) {
console.log(`[import] skipped "${line}"`);
continue;
}
await repo.save(show);
gzip.write(toCsvLine(show)); // NEW: returns false when full; ignored
}
gzip.end(); // NEW
await new Promise((resolve) => file.on("finish", resolve)); // NEW: wait for the file, not gzip
console.log("[import] done");
}
await writeFile("shows.csv", sampleCsv); // test data for this example
await importShows(readShowLines("shows.csv"), makeShowRepository(), "shows-clean.csv.gz");
console.log(gunzipSync(await readFile("shows-clean.csv.gz")).toString().trim());
Output:
[db] saved spring
[import] skipped "broken line"
[db] saved summer
[import] done
spring,Songs of Spring,2027-03-14,1200
summer,Summer Lights,2027-06-20,1500
It works on the test file, but it has four problems:
importShowscreates file objects again, so its test now needs a real folder.- The next output, a JSON file for a second partner, means a fourth parameter and more lines in the same loop.
gzip.write()returnsfalsewhen gzip cannot take more data yet, and the code ignores it. So on a slow disk, the archive text collects in memory.- The last
awaitmust wait for the file, not for gzip, because waiting for gzip ends the import before the last bytes are on disk.
Pause and predict: the loop now does five jobs (split, parse, save, format, compress). How would you cut it into steps that each do one job, and that each connect to the next one in the same way?
The idea: steps with an input side and an output side
A stream is Node.js’s built-in way to move data in chunks. Streams are not in the GoF book, because they come from Node.js itself. Node.js has three kinds that this module uses:
- A Readable stream is a source you read chunks from, such as a file being read.
- A Writable stream is a destination you write chunks to, such as a file being written.
- A Transform stream has both sides. You write chunks into one side, and changed chunks come out of the other.
Think of a ticket office that mails paper tickets. One person prints tickets, the next folds them into envelopes, and the next mails them. Each person takes work from a tray on one side and puts it in a tray on the other. In the same way, a Transform stream takes chunks from the step before it and passes chunks to the step after it.
So streams let you change the source, the destination and the order of the steps, without touching any step.
The fix: four small Transform streams
Each step becomes a function that returns a new Transform. Its transform method gets one chunk and calls done when it is finished, either with a value to pass on or with nothing. Inside it, this.push(value) passes on extra values. Save stages.ts:
import { Transform } from "node:stream";
import { StringDecoder } from "node:string_decoder";
import { parseShow, toCsvLine, type Show, type ShowRepository } from "./shows.ts";
// Bytes in, one line (a string) out per line of text
export function splitLines(): Transform {
const decoder = new StringDecoder("utf8"); // keeps a letter like "é" whole across chunks
let rest = "";
return new Transform({
readableObjectMode: true,
transform(chunk: Buffer, _encoding, done) {
const parts = (rest + decoder.write(chunk)).split("\n");
rest = parts.pop() ?? "";
for (const line of parts) this.push(line);
done();
},
flush(done) {
const last = rest + decoder.end();
if (last !== "") this.push(last);
done();
},
});
}
// Lines in, Show objects out; skips the header and bad lines
export function parseShows(): Transform {
let first = true;
return new Transform({
objectMode: true,
transform(line: string, _encoding, done) {
if (first || line === "") {
first = false;
return done();
}
const show = parseShow(line);
if (show === null) {
console.log(`[import] skipped "${line}"`);
return done();
}
done(null, show);
},
});
}
// Shows in, the same shows out, after each one is saved
export function saveShows(repo: ShowRepository): Transform {
return new Transform({
objectMode: true,
transform(show: Show, _encoding, done) {
repo.save(show).then(() => done(null, show), done);
},
});
}
// Shows in, CSV text out
export function toCsvLines(): Transform {
return new Transform({
writableObjectMode: true,
transform(show: Show, _encoding, done) {
done(null, toCsvLine(show));
},
});
}
What to notice in stages.ts:
- A chunk can end in the middle of a line, so
splitLineskeeps the unfinished part inrestfor the next chunk. Itsflushmethod runs once after the last chunk and passes on the last line. - Object mode means the chunks are JavaScript values, such as a
Show, instead of bytes (object mode). InsplitLines,readableObjectMode: truemeans bytes go in and strings come out.writableObjectMode: trueintoCsvLinesis the reverse. saveShowscallsdoneonly after the save finishes, and a failed save passes its error todone. That is how a Transform waits for async work.
Connect the steps with .pipe()
The connecting file uses .pipe(), which sends everything one stream outputs into the next one (readable.pipe()). finished from node:stream/promises returns a promise that settles when a stream is done. Save archive-pipe.ts:
import { createReadStream, createWriteStream } from "node:fs";
import { readFile, writeFile } from "node:fs/promises";
import { finished } from "node:stream/promises";
import { createGzip, gunzipSync } from "node:zlib";
import { makeShowRepository, sampleCsv } from "./shows.ts";
import { parseShows, saveShows, splitLines, toCsvLines } from "./stages.ts";
await writeFile("shows.csv", sampleCsv); // test data for this example
const archive = createReadStream("shows.csv")
.pipe(splitLines())
.pipe(parseShows())
.pipe(saveShows(makeShowRepository()))
.pipe(toCsvLines())
.pipe(createGzip())
.pipe(createWriteStream("shows-clean.csv.gz"));
await finished(archive); // waits until the last stream has written everything
console.log("[import] done");
console.log(gunzipSync(await readFile("shows-clean.csv.gz")).toString().trim());
The output is the same six lines as archive-before.ts. createGzip() fits in the chain with no adapter, because every zlib compressor inherits from stream.Transform.
Each stream keeps a small buffer, a queue of chunks that wait for the next step. Its size limit is the highWaterMark option, 64 KiB for byte streams and 16 items in object mode (buffering). The buffers let the steps work side by side. So parseShows can parse the next line while saveShows waits for the database.
This version handles a good night. Card 3 shows that .pipe() handles a bad night poorly, and replaces it. Figure 4 shows the structure before and after.
Before
[archive-before.ts] --> [importShows]
[importShows] split, parse, save, format, then gzip.write by hand
[importShows] ==> [createGzip] ==> [createWriteStream]
After
[archive-pipe.ts] ==> [createReadStream]
[archive-pipe.ts] ==> [splitLines] [parseShows] [saveShows] NEW
[toCsvLines] NEW
[archive-pipe.ts] ==> [createGzip] ==> [createWriteStream]
each [step] ..> [Transform] (I): a writable side and a readable side
Figure 4: one loop with five jobs became five steps that share one shape, and only the entry file knows the order.
Prove it with a test
A step can be tested with no file. Readable.from() turns an array, or any iterable, into a Readable stream in object mode. A Readable stream is also an async iterable, so for await collects the output. Save stages.test.ts:
import { test } from "node:test";
import assert from "node:assert/strict";
import { Readable } from "node:stream";
import { parseShows } from "./stages.ts";
import type { Show } from "./shows.ts";
test("parseShows turns lines into shows and drops the header", async () => {
const lines = Readable.from([
"id,title,date,priceCents",
"spring,Songs of Spring,2027-03-14,1200",
"broken line",
]);
const shows: Show[] = [];
for await (const show of lines.pipe(parseShows())) shows.push(show);
assert.deepEqual(shows, [
{ id: "spring", title: "Songs of Spring", date: "2027-03-14", priceCents: 1200 },
]);
});
Run it with npx tsx --test stages.test.ts:
[import] skipped "broken line"
✔ parseShows turns lines into shows and drops the header (2.243166ms)
ℹ tests 1
ℹ pass 1
ℹ fail 0
In archive-before.ts, parsing sat inside a loop that also saved, formatted and compressed. Testing it meant running all five jobs and reading a gzip file back.
The next change: the partner sends a gzipped file
The partner started to compress its nightly file, shows.csv.gz, to save upload time. Reading gzip is one more Transform, createGunzip(). Here is the part of archive-gzip-input.ts that differs from archive-pipe.ts, as an excerpt:
// Excerpt of archive-gzip-input.ts. The rest is the same as archive-pipe.ts,
// with createGunzip and gzipSync added to the node:zlib import.
await writeFile("shows.csv.gz", gzipSync(sampleCsv)); // test data, gzipped
const archive = createReadStream("shows.csv.gz")
.pipe(createGunzip()) // NEW
.pipe(splitLines())
.pipe(parseShows())
.pipe(saveShows(makeShowRepository()))
.pipe(toCsvLines())
.pipe(createGzip())
.pipe(createWriteStream("shows-clean.csv.gz"));
The output is the same six lines. The change is one line in the chain, plus the file name, and no step changed.
Use it when, skip it when
Use Readable and Transform streams when:
- the data comes from or goes to Node.js I/O: files, gzip, HTTP requests and responses, sockets
- the data is too large for memory, and each step needs only a few chunks at a time
- you want steps you can reorder, reuse in another import, and test alone
Skip them when the data fits in memory, or when your own code makes the items and uses them. Card 1’s async generators chain with no stream class, as in importShows(firstLines(readShowLines(path), 1), repo). For 40 shows, an array and a map are simpler than both.
The cost
Every step adds a buffer, so a chain of six steps holds up to six buffers of data at once. That is the price of letting steps work side by side. Node.js also types each chunk as any, because a stream can carry anything. So tsc does not check the types between steps, and only your tests do.
Stack traces from inside a stream show Node.js internals (node:internal/streams/...) between your frames. And the stream API is large, with events, modes, flush and highWaterMark, so a reader new to streams needs time with it.
Seen in the wild
- Node.js zlib: every compressor and decompressor inherits from
stream.Transform, which is whycreateGzip()sat in the chain with no extra code. - Node.js HTTP: an incoming request is an
http.IncomingMessage, which extendsstream.Readable. Express hands this same object to your route asreq, so the same steps could read an upload.
Often confused with
- An async generator (Card 1): pulls one item at a time and has no buffer. A stream reads ahead into a buffer and speaks the same interface as Node.js I/O.
- Decorator (Module 3): a decorator wraps one object and keeps its interface. A Transform sits between two streams and changes the data that passes through.
Exercise: drop shows that are already over
Write onlyFutureShows(today), a Transform that passes on a Show only if its date is on or after today. Dates are in the form YYYY-MM-DD. Where would it go in the chain?
Answer
Save future-shows.ts:
import { Readable, Transform } from "node:stream";
import type { Show } from "./shows.ts";
// Drops shows whose date is before `today` (dates are YYYY-MM-DD, so text order works)
export function onlyFutureShows(today: string): Transform {
return new Transform({
objectMode: true,
transform(show: Show, _encoding, done) {
if (show.date < today) return done();
done(null, show);
},
});
}
const shows: Show[] = [
{ id: "winter", title: "Winter Tales", date: "2026-01-10", priceCents: 1000 },
{ id: "spring", title: "Songs of Spring", date: "2027-03-14", priceCents: 1200 },
];
for await (const show of Readable.from(shows).pipe(onlyFutureShows("2026-11-15"))) {
console.log(`[filter] kept ${show.id}`);
}
Output:
[filter] kept spring
It goes after parseShows, because it needs Show objects, and before saveShows, so past shows are never saved. Calling done() with no value passes nothing on, which is how a Transform drops a chunk.
pipeline and backpressure
The pain: the bad night
One night the database went down after the first show. bad-night.ts runs the same chain as archive-pipe.ts, with a repository that fails on the second save. Maya had added an error listener on the last stream. Save bad-night.ts:
import { createReadStream, createWriteStream } from "node:fs";
import { writeFile } from "node:fs/promises";
import { finished } from "node:stream/promises";
import { createGzip } from "node:zlib";
import { sampleCsv, type ShowRepository } from "./shows.ts";
import { parseShows, saveShows, splitLines, toCsvLines } from "./stages.ts";
// A database that goes down after the first show
const brokenRepo: ShowRepository = {
async save(show) {
if (show.id !== "spring") throw new Error("database is down");
console.log(`[db] saved ${show.id}`);
},
};
await writeFile("shows.csv", sampleCsv);
const archive = createReadStream("shows.csv")
.pipe(splitLines())
.pipe(parseShows())
.pipe(saveShows(brokenRepo))
.pipe(toCsvLines())
.pipe(createGzip())
.pipe(createWriteStream("shows-clean.csv.gz"));
archive.on("error", (err) => console.log("[import] failed:", err.message));
await finished(archive);
console.log("[import] done");
Output of npx tsx bad-night.ts, shortened:
[db] saved spring
[import] skipped "broken line"
node:events:505
throw er; // Unhandled 'error' event
^
Error: database is down
at Object.save (bad-night.ts:11:37)
at Transform.transform (stages.ts:50:12)
Emitted 'error' event on Transform instance at:
at Transform.onerror (node:internal/streams/readable:1054:14)
The process crashed with exit code 1, the code a process returns when it fails. .pipe() does not pass an error from one stream to the next. The error happened in saveShows, which had no error listener, so Node.js threw it and the process stopped.
The listener on the last stream never ran, and neither did the “done” line. When one stream in a .pipe() chain fails, the other streams stay open, as the Node.js docs for readable.pipe() warn. You must close each one yourself.
Leo also had a second change request. Morning sales start at 06:00, so the import had to stop after a time limit. It also had to stop cleanly when the server shut down for a deploy, and the chain had no single place to stop it.
Pause and predict: you want one place that catches an error from any step, closes every stream, and can stop the whole chain on request. Where would that place be, and what would it need to know?
The idea: one call that owns the whole chain
pipeline from node:stream/promises takes a source, any number of steps and a destination. It connects them in order and returns one promise. That promise resolves when the destination has written everything.
If any stream fails, pipeline closes every stream in the chain at once and rejects with that error. Node.js calls this destroying a stream, and it frees what the stream holds, such as an open file. pipeline also takes an AbortSignal (Module 1) as its signal option. When the signal aborts, pipeline destroys the chain and rejects with an error named AbortError.
Go back to the ticket office from Card 2, and add a shift lead who watches the whole line. If one person cannot go on, the shift lead stops everyone and clears the tables. At 06:00, the shift lead stops the line on time. pipeline is the shift lead, destroying the streams is clearing the tables, and the signal is the clock.
So pipeline lets you change the list of steps, and when the import stops, with no error or cleanup code in any step.
The fix: one pipeline with a signal
The import becomes one function that takes its source, its repository and its destination from the caller, as Module 6 taught. Save import-pipeline.ts:
import type { Readable, Writable } from "node:stream";
import { pipeline } from "node:stream/promises";
import { createGzip } from "node:zlib";
import type { ShowRepository } from "./shows.ts";
import { parseShows, saveShows, splitLines, toCsvLines } from "./stages.ts";
// One call connects the stages, waits for the end, and reports one error
export async function importToArchive(
input: Readable,
repo: ShowRepository,
archive: Writable,
signal: AbortSignal,
): Promise<void> {
await pipeline(
input,
splitLines(),
parseShows(),
saveShows(repo),
toCsvLines(),
createGzip(),
archive,
{ signal },
);
}
And run-pipeline.ts, which creates the real parts:
import { createReadStream, createWriteStream } from "node:fs";
import { readFile, writeFile } from "node:fs/promises";
import { gunzipSync } from "node:zlib";
import { importToArchive } from "./import-pipeline.ts";
import { makeShowRepository, sampleCsv } from "./shows.ts";
await writeFile("shows.csv", sampleCsv); // test data for this example
try {
await importToArchive(
createReadStream("shows.csv"),
makeShowRepository(),
createWriteStream("shows-clean.csv.gz"),
AbortSignal.timeout(10 * 60 * 1000), // stop after ten minutes
);
console.log("[import] done");
console.log(gunzipSync(await readFile("shows-clean.csv.gz")).toString().trim());
} catch (err: unknown) {
console.log("[import] failed:", err instanceof Error ? err.message : err);
process.exitCode = 1;
}
On a good night it prints the same six lines as archive-pipe.ts. AbortSignal.timeout(ms) from Module 1 makes a signal that aborts after that many milliseconds, here ten minutes. Now the bad night. Save bad-night-pipeline.ts:
import { createReadStream, createWriteStream } from "node:fs";
import { writeFile } from "node:fs/promises";
import { importToArchive } from "./import-pipeline.ts";
import { sampleCsv, type ShowRepository } from "./shows.ts";
// The same database that goes down after the first show
const brokenRepo: ShowRepository = {
async save(show) {
if (show.id !== "spring") throw new Error("database is down");
console.log(`[db] saved ${show.id}`);
},
};
await writeFile("shows.csv", sampleCsv);
const input = createReadStream("shows.csv");
const archive = createWriteStream("shows-clean.csv.gz");
try {
await importToArchive(input, brokenRepo, archive, AbortSignal.timeout(600_000));
} catch (err: unknown) {
console.log("[import] failed:", err instanceof Error ? err.message : err);
}
console.log("input closed:", input.destroyed, "| archive closed:", archive.destroyed);
Output:
[db] saved spring
[import] skipped "broken line"
[import] failed: database is down
input closed: true | archive closed: true
The error from the middle step reached the one catch. Both files were closed, and the process kept running. Figure 5 shows the structure before and after.
Before
[archive-pipe.ts] --> .pipe() x6 --> [createWriteStream]
[archive-pipe.ts] --> [finished] watches only the last stream
no owner for errors, no way to stop
After
[run-pipeline.ts] ==> [createReadStream] [createWriteStream]
[run-pipeline.ts] ==> [AbortSignal.timeout] NEW
[run-pipeline.ts] --> [importToArchive] --> [pipeline] NEW
[pipeline] --> every step, in order; one promise, one error
Figure 5: pipeline becomes the one owner of the chain; the steps themselves did not change.
Figure 6 follows the bad night through pipeline, step by step.
1 [bad-night-pipeline.ts] --> [importToArchive] --> [pipeline]: 7 streams
~ await: the one promise ~
2 [parseShows] passes spring --> [saveShows] --> [repo] save(spring)
~ await ~ saved
3 [parseShows] skips "broken line", passes summer
4 [saveShows] --> [repo] save(summer)
~ await ~ rejects: "database is down"
5 [saveShows] calls done(error); the stream emits "error"
6 [pipeline] destroys all 7 streams; the files close
7 [pipeline] rejects its promise; [bad-night-pipeline.ts] catches one error
Figure 6: the error travels from one step to pipeline, and pipeline closes every stream before the caller hears about it.
Backpressure: a slow step makes the others wait
pipeline does one more job, and it is easiest to see with a slow destination. This demo has six rows and a database that takes 10 ms per save.
The first mode uses a common mistake, an async listener on the "data" event, which a Readable stream emits for each chunk. The second mode uses pipeline and a Writable destination with highWaterMark: 2. Save backpressure.ts:
import { Readable, Writable } from "node:stream";
import { pipeline } from "node:stream/promises";
import { setTimeout as sleep } from "node:timers/promises";
// The source: logs each row when a stage asks for it
function rows(): Readable {
async function* generate(): AsyncGenerator<string> {
for (let n = 1; n <= 6; n++) {
console.log(`read row ${n}`);
yield `row ${n}`;
}
}
return Readable.from(generate(), { highWaterMark: 1 });
}
// A slow database: each save takes 10 ms
async function slowSave(row: string): Promise<void> {
await sleep(10);
console.log(`saved ${row}`);
}
const mode = process.argv[2];
if (mode === "pipeline") {
const saver = new Writable({
objectMode: true,
highWaterMark: 2, // at most 2 rows wait in front of the database
write(row: string, _encoding, done) {
slowSave(row).then(() => done(), done);
},
});
await pipeline(rows(), saver);
} else {
// The common mistake: an async listener on "data" (nobody waits for it)
rows().on("data", async (row: string) => {
await slowSave(row);
});
}
Pause and predict: both modes read six rows, and each save takes 10 ms. In each mode, how many rows are read before the first
savedline prints? Write your answers, then run both modes.
Output of npx tsx backpressure.ts, then npx tsx backpressure.ts pipeline, side by side:
"data" listener pipeline
read row 1 read row 1
read row 2 read row 2
read row 3 read row 3
read row 4 saved row 1
read row 5 saved row 2
read row 6 read row 4
saved row 1 read row 5
saved row 2 saved row 3
saved row 3 saved row 4
saved row 4 read row 6
saved row 5 saved row 5
saved row 6 saved row 6
With the listener, the stream reads all six rows before the first save ends. A stream does not wait for the promise that an async listener returns, so every row starts its own save at once. With two million rows, that is two million saves in progress and two million rows in memory. If one save fails, its rejected promise has no handler, so it becomes an unhandled rejection, a failure that no code catches.
With pipeline, reading stays at most three rows ahead of saving. Two rows wait in the Writable’s buffer, and one waits in the source’s buffer.
This is backpressure, a slow step’s way of making the steps before it wait. When a stream’s buffer reaches its highWaterMark, write() returns false. The writer must then stop until the stream emits "drain", which means there is room again, as the Node.js docs on buffering describe. pipeline and .pipe() both obey this for you, but code that calls write() by hand, as archive-before.ts did, must obey it itself.
Figure 7 shows where the “wait” signal travels.
data flows this way ------------------------------------------->
[createReadStream] --> [splitLines] --> [parseShows] --> [saveShows]
^ ^ ^ |
| | | slow database:
+---- buffer full ---+---- full ------+---- full ----+
<----------------------- "wait" flows this way ---------------
A step reads only when its out-buffer has room.
The file is read no faster than the database can save.
Figure 7: backpressure flows against the data, from the slowest step back to the file.
Rule: Let
pipelinemove the data, and never put anasynclistener on"data".
Prove it with a test
The test passes a Readable made from a string, a fake repository and a PassThrough as the archive. A PassThrough is a Transform that passes data on unchanged, and here it stands in for the file. Save import-pipeline.test.ts:
import { test } from "node:test";
import assert from "node:assert/strict";
import { PassThrough, Readable } from "node:stream";
import { importToArchive } from "./import-pipeline.ts";
import type { ShowRepository } from "./shows.ts";
const csv = "id,title,date,priceCents\nspring,Songs of Spring,2027-03-14,1200\n";
test("a failing save rejects the whole import with that error", async () => {
const fakeRepo: ShowRepository = {
async save() {
throw new Error("database is down");
},
};
const run = importToArchive(Readable.from([csv]), fakeRepo, new PassThrough(), new AbortController().signal);
await assert.rejects(run, { message: "database is down" });
});
test("an aborted signal stops the import before any save", async () => {
const saved: string[] = [];
const fakeRepo: ShowRepository = {
async save(show) {
saved.push(show.id);
},
};
const run = importToArchive(Readable.from([csv]), fakeRepo, new PassThrough(), AbortSignal.abort());
await assert.rejects(run, { name: "AbortError" });
assert.deepEqual(saved, []);
});
Run it with npx tsx --test import-pipeline.test.ts:
✔ a failing save rejects the whole import with that error (3.948958ms)
✔ an aborted signal stops the import before any save (0.931667ms)
ℹ tests 2
ℹ pass 2
ℹ fail 0
AbortSignal.abort() makes a signal that is already aborted. The “before” chain could not be tested for failure at all, because the error crashed the test process.
The next change: also stop when the server shuts down
A deploy sends the process a SIGTERM signal, the operating system’s request to stop. The import had to stop on that, as well as on the time limit. AbortSignal.any() makes one signal that aborts when any of its input signals aborts. Save run-shutdown.ts:
import { createReadStream, createWriteStream } from "node:fs";
import { writeFile } from "node:fs/promises";
import { setTimeout as sleep } from "node:timers/promises";
import { importToArchive } from "./import-pipeline.ts";
import { sampleCsv, type ShowRepository } from "./shows.ts";
const slowRepo: ShowRepository = {
async save(show) {
await sleep(50); // a slow database, so the stop arrives mid-import
console.log(`[db] saved ${show.id}`);
},
};
// NEW: stop on the time limit OR when the server is asked to shut down
const shutdown = new AbortController();
process.once("SIGTERM", () => shutdown.abort());
const signal = AbortSignal.any([AbortSignal.timeout(10 * 60 * 1000), shutdown.signal]);
await writeFile("shows.csv", sampleCsv);
setTimeout(() => process.kill(process.pid, "SIGTERM"), 70); // test: shut down at 70 ms
try {
await importToArchive(
createReadStream("shows.csv"),
slowRepo,
createWriteStream("shows-clean.csv.gz"),
signal,
);
console.log("[import] done");
} catch (err: unknown) {
if (err instanceof Error && err.name === "AbortError") console.log("[import] stopped early");
else throw err;
}
Output:
[import] skipped "broken line"
[db] saved spring
[import] stopped early
[db] saved summer
Three lines changed in the entry file, and importToArchive did not change.
Look at the last line. The summer save had already started when the signal fired, so it finished after the import stopped. pipeline destroys the streams, but it cannot cancel a promise that is already running inside a step. If a save must stop too, pass the signal into repo.save, as fetchSeatMap took a signal in Module 1.
Steps written as functions
The fix used stream objects for every step, but pipeline also accepts functions. A middle step can be an async generator that takes an async iterable and yields values. The last step can be an async function, and pipeline waits for its promise. This form joins Card 1 and Card 3.
Save pipeline-functions.ts:
import { createReadStream } from "node:fs";
import { writeFile } from "node:fs/promises";
import { pipeline } from "node:stream/promises";
import { makeShowRepository, parseShow, sampleCsv, type Show } from "./shows.ts";
import { splitLines } from "./stages.ts";
const repo = makeShowRepository();
await writeFile("shows.csv", sampleCsv);
await pipeline(
createReadStream("shows.csv"),
splitLines(),
// A transform written as an async generator: lines in, shows out
async function* (lines: AsyncIterable<string>): AsyncGenerator<Show> {
let first = true;
for await (const line of lines) {
if (first || line === "") {
first = false;
continue;
}
const show = parseShow(line);
if (show === null) console.log(`[import] skipped "${line}"`);
else yield show;
}
},
// The last stage as an async function: pipeline waits for its promise
async function (shows: AsyncIterable<Show>): Promise<void> {
for await (const show of shows) await repo.save(show);
},
{ signal: AbortSignal.timeout(10 * 60 * 1000) },
);
console.log("[import] done");
Output:
[db] saved spring
[import] skipped "broken line"
[db] saved summer
[import] done
Here TypeScript checks the types between the two function steps, because they are plain functions. Prefer this form for steps you write yourself and use in one pipeline. Keep stream objects for steps you reuse outside a pipeline, as stages.test.ts did, and for built-in streams such as gzip and files.
Use it when, skip it when
Use pipeline whenever you connect two or more streams. Signs in code that you need it:
- a chain of
.pipe()calls, with.on("error")on some streams and not others stream.on("data", async ...), an async listener the stream never waits forwrite()in a loop with its return value ignored- a long job with no way to stop it, or files left open after a failure
Skip it when there is no stream to connect. A for await loop over one async generator, as in Card 1, needs no pipeline. Its errors already reach your try/catch, and the generator’s own await makes the source wait with no extra code.
The cost
pipeline destroys every stream on failure, so a half-written archive stays on disk. If that matters, write to a temporary name and rename the file after success.
One bad step stops the whole night’s import, even if the other rows were fine. If you want to skip bad rows, handle them inside the step, as parseShows does.
A small highWaterMark keeps memory low but adds more waits. This module did not measure that trade, so it gives no numbers. Stack traces from a failed pipeline show the step that failed, not the line that called pipeline.
Seen in the wild
- Node.js itself: the
pipelinedocs use this same shape, a file read through gzip into a file, with asignaloption. - The Node.js guide Backpressuring in Streams explains how
write(),highWaterMarkand"drain"work together, and recommendspipelineover.pipe().
Often confused with
.pipe(): connects streams and obeys backpressure, but does not pass errors on or close the other streams.- Chain of Responsibility and Middleware (Module 5): a request passes along a chain, and any handler can stop it. In a pipeline every item passes through every step, many items are in the chain at once, and a slow step slows the steps before it.
Exercise: a file that is not there
The partner forgot to upload the file. Predict what importToArchive does with createReadStream("missing.csv") as its input, and what run-pipeline.ts‘s catch prints. Then try it.
Answer
The read stream fails when it tries to open the file, and it emits "error". pipeline destroys the other streams and rejects with that error. With the same try/catch as run-pipeline.ts, the output is:
[import] failed: ENOENT: no such file or directory, open 'missing.csv'
No show is saved, because no line was ever read. The empty shows-clean.csv.gz file is still created, since createWriteStream opens it at once. The cost section above explains why it stays.
Pipes and Filters
Pipes and Filters is an architecture style in which data flows through a line of independent steps, called filters, joined by connections called pipes. Each filter reads input, changes it and writes output. Hohpe and Woolf describe it for messaging in Enterprise Integration Patterns. Figure 8 shows the nightly import as Pipes and Filters.
[createReadStream] -pipe-> [splitLines] -pipe-> [parseShows] -pipe->
[saveShows] -pipe-> [toCsvLines] -pipe-> [createGzip] -pipe->
[createWriteStream]
each [filter] knows only its input and its output
Figure 8: the whole module as one chain; streams are the filters, and buffers with backpressure are the pipes.
A Unix shell command is a familiar example. gunzip -c shows.csv.gz | grep spring | wc -l joins three programs with |. In Node.js, pipeline with Transform streams is this style. You need it when a job changes data in several steps that you want to reorder, reuse or test one at a time.
Side by side
| Async iterator | Readable and Transform streams | pipeline and backpressure | |
|---|---|---|---|
| The problem it solves | A loop needs the whole array before it starts | Steps tied together in one loop; Node.js I/O to connect | Errors lost between steps, streams left open, no way to stop |
| What it lets you change | Where items come from | The source, destination and order of steps | The steps and the stop rule, with no cleanup code in steps |
| Who moves the data | The loop pulls with next() |
Each stream reads ahead into its buffer | pipeline connects; the slowest step decides the speed |
| Its cost | One promise per item; generator frames in stack traces | Buffers per step; chunks typed any; a large API |
One bad step stops all; half-written files stay |
Figure 9 is the decision figure for this module. It starts from the data in front of you.
You must process a set of items (rows, orders, lines)
|
v
Is it small, and already in memory? --yes--> No pattern needed.
| no An array and a loop.
v
Does your own code make the items and use them? --yes--> Async generator
| no (files, gzip, HTTP, sockets) and for await.
v
Do several steps change the data on the way? --no--> One stream and for await.
| yes
v
Transform streams or async generator steps, joined by pipeline
with a signal. Never .pipe() alone, never on("data", async ...).
Figure 9: most data needs no streams; reach for pipeline when Node.js I/O and several steps meet.
Check yourself
- Why does
readFileplussplit("\n")use more memory as the file grows? - What does an async generator do when it reaches
yield, and why does that save memory? - In a Transform stream, what does calling
done()with no value do? - Name two ways code can break backpressure.
- When a step in a
.pipe()chain fails, what happens to the other streams, and what doespipelinedo instead?
Answers
- It holds the whole file as one string, and again as an array of lines, until the loop ends. A large enough file also passes the limit on string length, and then
readFilethrows. - It hands one value to the loop and pauses until the loop asks for the next one. It reads nothing more while the loop is busy, so only the current item is in memory.
- It passes nothing on, so the chunk is dropped.
parseShowsandonlyFutureShowsdrop bad or past rows this way. - Any two of these: an
asynclistener on"data", which the stream never waits for; callingwrite()and ignoring afalseresult; reading a whole file at once. - With
.pipe(), the other streams stay open, and the error is thrown if the failing stream has no listener, which crashes the process.pipelinedestroys every stream and rejects its one promise with the error.
Lab: a sales report that streams
Time: about 20 minutes. Put the files next to stages.ts and shows.ts.
Each night TinyTickets also builds a sales report from an orders export. Here is sales-report.ts:
import { readFile } from "node:fs/promises";
// Paid totals per show, from an orders export
export async function salesReport(path: string): Promise<Map<string, number>> {
const text = await readFile(path, "utf8");
const totals = new Map<string, number>();
for (const line of text.split("\n")) {
const [, showId, , totalCents, status] = line.split(",");
if (!showId || status !== "paid") continue; // also skips the header
totals.set(showId, (totals.get(showId) ?? 0) + Number(totalCents));
}
return totals;
}
And run-sales-report.ts:
import { writeFile } from "node:fs/promises";
import { salesReport } from "./sales-report.ts";
const ordersCsv = [
"orderId,showId,quantity,totalCents,status",
"o1,spring,2,2550,paid",
"o2,spring,4,4800,paid",
"o3,summer,1,1650,cancelled",
"o4,summer,2,3150,paid",
].join("\n") + "\n";
await writeFile("orders.csv", ordersCsv); // test data for this example
const totals = await salesReport("orders.csv");
for (const [showId, cents] of totals) console.log(`${showId}: ${cents} cents`);
Output:
spring: 7350 cents
summer: 3150 cents
Here is the change request. The orders export is now large, and it arrives gzip-compressed as orders.csv.gz. The report must read it as a stream, and it must stop when its AbortSignal aborts. Split the code so that the adding-up rule can be tested with no file. Refactor sales-report.ts so that this test file, sales-report.test.ts, passes:
import { test } from "node:test";
import assert from "node:assert/strict";
import { Readable } from "node:stream";
import { gzipSync } from "node:zlib";
import { salesReport, sumSales } from "./sales-report.ts";
const ordersCsv = [
"orderId,showId,quantity,totalCents,status",
"o1,spring,2,2550,paid",
"o2,spring,4,4800,paid",
"o3,summer,1,1650,cancelled",
"o4,summer,2,3150,paid",
].join("\n") + "\n";
test("sumSales adds up paid orders per show", async () => {
async function* lines(): AsyncGenerator<string> {
yield* ordersCsv.split("\n");
}
const totals = await sumSales(lines());
assert.deepEqual([...totals], [["spring", 7350], ["summer", 3150]]);
});
test("salesReport reads a gzipped stream", async () => {
const input = Readable.from([gzipSync(ordersCsv)]);
const totals = await salesReport(input, new AbortController().signal);
assert.deepEqual([...totals], [["spring", 7350], ["summer", 3150]]);
});
test("salesReport stops when the signal is aborted", async () => {
const input = Readable.from([gzipSync(ordersCsv)]);
await assert.rejects(salesReport(input, AbortSignal.abort()), { name: "AbortError" });
});
Run it with npx tsx --test sales-report.test.ts, and check types with npx tsc --noEmit. Against the “before” file, the test file does not even load, because sumSales does not exist. Then update run-sales-report.ts to write orders.csv.gz and print the same two lines.
Pause and predict: before you start, list what changes (the source, compression, size) and what stays the same (the adding-up rule). Which of this module’s three cards do you need?
Hint 1
The rule that stays is the loop body: split the line, keep paid orders, add to the map. Move it into sumSales(lines: AsyncIterable<string>), and change for to for await.
Hint 2
salesReport takes a Readable and a signal now, not a path. Its steps are the input, createGunzip() and splitLines() from stages.ts.
Hint 3
The last step of a pipeline can be an async function that receives the lines as an async iterable. Inside it, call sumSales and keep its result in a variable that salesReport returns after pipeline finishes. Pass { signal } as the last argument.
Solution
sales-report.ts:
import type { Readable } from "node:stream";
import { pipeline } from "node:stream/promises";
import { createGunzip } from "node:zlib";
import { splitLines } from "./stages.ts";
// The rule that stays: paid totals per show, from any lines
export async function sumSales(lines: AsyncIterable<string>): Promise<Map<string, number>> {
const totals = new Map<string, number>();
for await (const line of lines) {
const [, showId, , totalCents, status] = line.split(",");
if (!showId || status !== "paid") continue; // also skips the header
totals.set(showId, (totals.get(showId) ?? 0) + Number(totalCents));
}
return totals;
}
// The plumbing: gzipped bytes in, lines out, then sumSales at the end
export async function salesReport(input: Readable, signal: AbortSignal): Promise<Map<string, number>> {
let totals = new Map<string, number>();
await pipeline(
input,
createGunzip(),
splitLines(),
async function (lines: AsyncIterable<string>): Promise<void> {
totals = await sumSales(lines);
},
{ signal },
);
return totals;
}
run-sales-report.ts:
import { createReadStream } from "node:fs";
import { writeFile } from "node:fs/promises";
import { gzipSync } from "node:zlib";
import { salesReport } from "./sales-report.ts";
const ordersCsv = [
"orderId,showId,quantity,totalCents,status",
"o1,spring,2,2550,paid",
"o2,spring,4,4800,paid",
"o3,summer,1,1650,cancelled",
"o4,summer,2,3150,paid",
].join("\n") + "\n";
await writeFile("orders.csv.gz", gzipSync(ordersCsv)); // test data, gzipped
const totals = await salesReport(createReadStream("orders.csv.gz"), AbortSignal.timeout(600_000));
for (const [showId, cents] of totals) console.log(`${showId}: ${cents} cents`);
Output of npx tsx run-sales-report.ts:
spring: 7350 cents
summer: 3150 cents
The tests pass with ℹ pass 3 and ℹ fail 0. You used all three cards. sumSales reads any async iterable (Card 1), so the first test feeds it a generator.
Gunzip and splitLines are Transform streams (Card 2). pipeline joins them, carries errors and obeys the signal (Card 3). So the rule and the plumbing are now in two functions, and only the plumbing knows about gzip.
The rule still trusts the export, so a totalCents that is not a number becomes NaN in the total, as before. Checking it is a real need, but the change request did not ask for it, and it would change the output for bad files. The solution also keeps the Map result, because the report holds a few numbers per show and fits in memory even when the export does not.
Which pattern, if any?
Scenario 1: Leo’s monthly list of shows
Leo wants a “Download my shows” link for organizers. It returns a CSV of one organizer’s shows, and an organizer has at most a few dozen. Here is the code Maya has so far, scenario-small.ts:
import { toCsvLine, type Show } from "./shows.ts";
// Leo's monthly list: one organizer, at most a few dozen shows
async function findShowsByOrganizer(organizerId: string): Promise<Show[]> {
console.log(`[db] shows for ${organizerId}`);
return [
{ id: "spring", title: "Songs of Spring", date: "2027-03-14", priceCents: 1200 },
{ id: "summer", title: "Summer Lights", date: "2027-06-20", priceCents: 1500 },
];
}
const shows = await findShowsByOrganizer("leo");
const csv = "id,title,date,priceCents\n" + shows.map(toCsvLine).join("");
process.stdout.write(csv); // in the route: res.type("text/csv").send(csv)
Output:
[db] shows for leo
id,title,date,priceCents
spring,Songs of Spring,2027-03-14,1200
summer,Summer Lights,2027-06-20,1500
A teammate suggests a Readable from the repository, a toCsvLines Transform and pipeline into the response, “so it scales”. Which pattern, if any?
Hint
Look at Figure 9. How big is the data, and where is it when the code runs?
Strong answer
No pattern is needed. A few dozen shows come back from one query as an array, and the CSV is a few kilobytes. Streams would add three more parts, buffers and any chunks, to save memory that is not at risk.
The signal to switch is a list with no fixed size, such as all orders of a show in Scenario 2. Then toCsvLine is already a separate function that a Transform can reuse.
Scenario 2: every order of a stadium show
For a stadium show, Leo wants a CSV of every order, up to 60,000 rows, downloaded from the browser. The repository from Module 7 can return orders a page at a time with findByShow(showId, offset, limit). If the organizer closes the browser tab, the export must stop reading from the database. Which pattern, if any?
Hint
Combine a source from Card 1 with the joining from Card 3. In an Express route, res is a Writable stream, and pipeline closes the chain if res closes early.
Strong answer
An async generator reads pages from the repository only when the next stage asks (Card 1). A second async generator turns orders into CSV lines. pipeline joins them to the response, with a signal (Card 3).
Save export-orders.ts. Here process.stdout stands in for res, and the repository is a fake that prints:
import { Readable, type Writable } from "node:stream";
import { pipeline } from "node:stream/promises";
type OrderStatus = "pending" | "paid" | "cancelled" | "refunded";
interface Order {
id: string;
showId: string;
buyerEmail: string;
quantity: number;
totalCents: number;
status: OrderStatus;
}
// Module 7's OrderRepository, cut down to findByShow, with paging added
interface OrderRepository {
findByShow(showId: string, offset: number, limit: number): Promise<Order[]>;
}
// The iterator: one page from the database at a time, only when asked
async function* ordersOf(repo: OrderRepository, showId: string): AsyncGenerator<Order> {
for (let offset = 0; ; offset += 2) {
const page = await repo.findByShow(showId, offset, 2);
if (page.length === 0) return;
yield* page;
}
}
async function* toCsv(orders: AsyncIterable<Order>): AsyncGenerator<string> {
yield "id,buyerEmail,quantity,totalCents,status\n";
for await (const o of orders) yield `${o.id},${o.buyerEmail},${o.quantity},${o.totalCents},${o.status}\n`;
}
export async function exportOrders(repo: OrderRepository, showId: string, res: Writable, signal: AbortSignal): Promise<void> {
await pipeline(Readable.from(ordersOf(repo, showId)), toCsv, res, { signal });
}
const orders: Order[] = [
{ id: "o1", showId: "spring", buyerEmail: "ana@example.com", quantity: 2, totalCents: 2550, status: "paid" },
{ id: "o2", showId: "spring", buyerEmail: "ben@example.com", quantity: 4, totalCents: 4800, status: "paid" },
{ id: "o3", showId: "spring", buyerEmail: "chi@example.com", quantity: 1, totalCents: 1350, status: "refunded" },
];
const fakeRepo: OrderRepository = {
async findByShow(showId, offset, limit) {
console.error(`[db] page at ${offset}`);
return orders.filter((o) => o.showId === showId).slice(offset, offset + limit);
},
};
await exportOrders(fakeRepo, "spring", process.stdout, AbortSignal.timeout(60_000));
Output:
id,buyerEmail,quantity,totalCents,status
[db] page at 0
o1,ana@example.com,2,2550,paid
[db] page at 2
o2,ben@example.com,4,4800,paid
[db] page at 4
o3,chi@example.com,1,1350,refunded
The page size is 2 to show the paging, and real code would use a few hundred. Pages are fetched only as the response accepts more data, so a slow browser slows the database reads (Figure 7). If the tab closes, res closes, pipeline destroys the chain, and the generator stops asking for pages. The fake prints to console.error so its lines stay out of the CSV.
Copy this prompt into an AI assistant to get feedback on your answers:
I am learning design patterns in TypeScript and Node.js. Module 8 taught
async iterators (async generators, for await), Readable and Transform
streams, and pipeline with backpressure and AbortSignal. For each scenario
below, I wrote which pattern I would use, or "no pattern", and why.
Please check my reasoning: did I pick the simplest option that handles the
data size, errors and cancellation? Point out anything I missed, such as
backpressure, unhandled errors or memory. Do not write the full solution.
Scenario 1 (CSV of one organizer's few dozen shows): <your answer>
Scenario 2 (CSV of up to 60,000 orders to the browser): <your answer>
Going deeper
You can skip this section. It covers details the cards above left out.
The limit on string length
A JavaScript string cannot be longer than buffer.constants.MAX_STRING_LENGTH. That is about 512 million characters on 64-bit systems, and 536,870,888 on Node.js 24. Past that size, readFile(path, "utf8") throws instead of returning a string.
Commas inside quotes
parseShow splits on commas and nothing more. But real CSV files can put a comma inside quotes, as in "Songs, Old and New". When organizers send files like that, use csv-parse, an npm package that reads CSV text, quotes included.
Leaving a for await loop early
Leaving a for await loop with break or return calls the iterator’s return() method. For readline, the readline docs say this calls rl.close(). That is why firstLines in the Card 1 exercise also stops the file reader. If you write your own iterator class, you must write that return() method yourself.
Iterator and Transform as classes
The GoF book writes Iterator as a class, an object that keeps its position in fields and answers next(). For the partner pages, that class needs two counters, a while loop and a hand-built { done, value } result to do what one yield* does. So prefer the generator. Write the class form when the iterator needs extra public methods, or when you read library code written before generators existed.
A Transform can also be a class that extends Transform and keeps its state in a field, such as private first = true. The method must then be named _transform, with an underscore, as the Node.js API for stream implementers asks. The class is longer than the function form. Write one when a step has several methods or a lifecycle, or when you publish it as a library.
Characters cut across chunks
A character such as “é” takes more than one byte, and a chunk boundary can fall between those bytes. The StringDecoder in splitLines holds back an unfinished character until the next chunk completes it.
The error a timeout gives
When AbortSignal.timeout stops the import, the error is still an AbortError. Its cause property holds the timeout’s reason.
Where Pipes and Filters comes from
Buschmann and others named Pipes and Filters in Pattern-Oriented Software Architecture, Volume 1 (1996).
Cheat sheet
| Pattern or tool | The problem it answers | The signal in your code |
|---|---|---|
| Async iterator (Iterator, GoF) | A loop needs all the data before it starts | readFile then split("\n"); a paged API loaded into one array |
| Async generator | You need your own one-at-a-time source | A manual page++ loop that fills an array |
| Readable and Transform streams | Steps tied together in one loop; Node.js I/O to connect | A loop that parses, saves, formats and compresses |
pipeline |
Errors lost between steps; streams left open | .pipe().pipe() with on("error") on some streams |
| Backpressure | A fast source floods a slow step | on("data", async ...); write() result ignored |
AbortSignal |
A long job cannot be stopped | A nightly job with no time limit and no shutdown handling |
| Pipes and Filters | Several steps you want to reorder and test alone | A chain of transforms from a source to a destination |
| No pattern | The data is small and already in memory | One query returns an array of a few dozen rows |
- One at a time: an async generator pauses at each
yield, so memory depends on one item, not on the whole file. - One job per step: a Transform step can be reordered, reused and tested with
Readable.from()and no file. - One owner:
pipelinewith asignalsends any error to onecatch, closes every stream, and stops on request. - Backpressure: never put an
asynclistener on"data"or ignore afalsefromwrite(), because a slow step must make the others wait. - No pattern: a few dozen rows already in memory need only an array and a loop.
Next, try Module 9, which shows what Timeout, Retry and Circuit Breaker do when the TinyTickets seat-map service does not answer.
Sources
- Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides, Design Patterns: Elements of Reusable Object-Oriented Software, Addison-Wesley, 1994. The Iterator pattern.
- Frank Buschmann, Regine Meunier, Hans Rohnert, Peter Sommerlad, Michael Stal, Pattern-Oriented Software Architecture, Volume 1: A System of Patterns, Wiley, 1996. The Pipes and Filters pattern.
- Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, Addison-Wesley, 2003: Pipes and Filters.
- Node.js documentation: stream, streams promises API,
stream.pipeline, buffering, object mode,Readable.from,readable[Symbol.asyncIterator],readable.pipe, readline async iterator, zlib, string decoder,buffer.constants.MAX_STRING_LENGTH,AbortSignal.any,events.on,http.IncomingMessage. - Node.js guide: Backpressuring in Streams.
- MDN: iteration protocols,
for await...of,async function*. - csv-parse: csv.js.org/parse.