Sub topic 10
Async Iterables You Already Have: Streams and readline
You don't need to write your own async iterable for most I/O. Node.js readable streams, readline interfaces, and WHATWG ReadableStream objects (the kind fetch() gives you as response.body) all implement Symbol.asyncIterator. That means for await...of can read them directly. This chapter covers what each source yields, how the loop interacts with buffering and backpressure, and what happens to the underlying resource when you break out of the loop or an error occurs.
This chapter assumes you know for await...of, the return() method, and cleanup on early exit from earlier chapters. It also assumes you can run ES module scripts in Node.js 18 or later (a .mjs file, or "type": "module" in package.json), because the examples use top-level await.
What the Built-in Sources Yield
Each source decides what one "value" is. Getting this wrong is the most common bug: you expect lines and get arbitrary chunks of bytes.
| Source | How you get it | Each value is | Early `break` does |
|---|---|---|---|
| `fs.createReadStream(path)` | `node:fs` | a `Buffer` chunk, or a string if `encoding` is set | destroys the stream and closes the file |
| Any Node.js `Readable` in object mode | `Readable.from()`, parsers, DB drivers | one JavaScript value per push | destroys the stream |
| `readline.createInterface({ input })` | `node:readline` | one line as a string, with no newline | closes the interface |
| `filehandle.readLines()` | `node:fs/promises` (Node 18.11+) | one line as a string | closes the interface |
| WHATWG `ReadableStream` | `response.body`, `new ReadableStream()` | whatever was enqueued, often `Uint8Array` | cancels the stream |
| `events.on(emitter, name)` | `node:events` | an array of the event's arguments | removes the listener |
| `fs.promises.opendir(path)` | `node:fs/promises` | a `Dirent` for each directory entry | closes the directory handle |
Reading a Node.js Stream Chunk by Chunk
A readable stream delivers data in chunks. The chunk size is set by highWaterMark, which defaults to 64 KiB for file streams. If you set encoding, you get strings and not Buffers.
import { createReadStream, writeFileSync } from 'node:fs';
writeFileSync('sample.txt', 'line one\nline two\nline three\n');
const stream = createReadStream('sample.txt', {
encoding: 'utf8',
highWaterMark: 8 // tiny chunks so the boundaries are visible
});
for await (const chunk of stream) {
console.log(JSON.stringify(chunk));
}
// "line one"
// "\nline tw"
// "o\nline t"
// "hree\n"The chunk boundaries have nothing to do with line boundaries. Chunks don't line up with characters either, unless you set encoding. Without it you get raw Buffers, and a multi-byte UTF-8 character can be split across two of them. Calling chunk.toString() on each piece then corrupts that character. Either set encoding, or pipe the bytes through a decoder that remembers partial characters between chunks.
Backpressure comes for free
The async iterator controls the flow of data. When you pull from a stream with for await...of, the stream only reads ahead until its internal buffer reaches highWaterMark, then it pauses. If your loop body awaits something slow, such as a database insert, the stream doesn't keep filling memory. It waits for the next next() call.
Compare this with the older stream.on('data', handler) style. An event handler can't make the stream wait for an async operation to finish. To get backpressure there, you call pause() and resume() yourself. With for await...of, the pull model handles it.
Reading Lines with readline
To work with lines, wrap the stream in a readline interface. The interface is async iterable and yields one string per line, with the line terminator removed.
import { createReadStream, writeFileSync } from 'node:fs';
import { createInterface } from 'node:readline';
writeFileSync('data.txt', 'alice,30\r\nbob,25\r\n\r\ncarol,41\r\n');
const rl = createInterface({
input: createReadStream('data.txt'),
crlfDelay: Infinity
});
let total = 0;
let lineCount = 0;
for await (const line of rl) {
lineCount++;
if (line.trim() === '') continue; // skip blank lines
const [name, age] = line.split(',');
total += Number(age);
console.log(name, age);
}
console.log(`Lines: ${lineCount}, total age: ${total}`);
// alice 30
// bob 25
// carol 41
// Lines: 4, total age: 96crlfDelay: Infinity makes readline treat every \r\n as a single line break. Without it, a \r and \n that arrive with more than 100 ms between them can be counted as two breaks, which gives you phantom empty lines. Always set it when you read files.
On Node.js 18.11 and later, FileHandle.readLines() is a shorter way to do the same thing:
import { open, writeFile } from 'node:fs/promises';
await writeFile('data.txt', 'first\nsecond\nthird\n');
const file = await open('data.txt');
for await (const line of file.readLines()) {
console.log(line);
}
// first
// second
// thirdThe Node.js documentation also notes that async iteration over readline is slower than listening to the 'line' event. For most scripts the difference doesn't matter. If you parse multi-gigabyte logs and profiling shows readline as the bottleneck, consider splitting raw chunks yourself or using a dedicated parser.
Errors from Streams
When a stream emits 'error', the pending next() promise rejects, so the error is thrown at the for await...of line. An ordinary try/catch handles it, just as with the async generators in the earlier error-handling chapter.
import { createReadStream } from 'node:fs';
try {
for await (const chunk of createReadStream('does-not-exist.txt')) {
console.log(chunk.length);
}
} catch (err) {
console.error('Read failed:', err.code); // Read failed: ENOENT
}The stream is destroyed when the error is thrown, so there is no file descriptor left to close. This is a real advantage over event-based code. With events, forgetting an 'error' listener crashes the process, and forgetting to destroy the stream leaks the handle.
Breaking Out Destroys the Stream
When the loop exits early through break, return, or an exception in the loop body, for await...of calls the iterator's return() method. For Node.js streams, return() destroys the stream. For readline, it closes the interface.
import { createReadStream, writeFileSync } from 'node:fs';
writeFileSync('big.txt', 'x'.repeat(1_000_000));
const stream = createReadStream('big.txt');
let chunks = 0;
for await (const chunk of stream) {
chunks++;
if (chunks === 2) break;
}
console.log(chunks, stream.destroyed); // 2 trueUsually this is what you want: you read the header of a large file and the file handle is released at once. It does mean a stream can't be reused after a break. If you start a second for await...of over the same stream, it ends immediately, or throws an error if the stream was destroyed with one.
To keep the stream alive, Node.js offers stream.iterator({ destroyOnReturn: false }). The API is marked experimental, so check the documentation for your Node.js version before you depend on it.
import { Readable } from 'node:stream';
const source = Readable.from(['header', 'row1', 'row2', 'row3']);
for await (const item of source.iterator({ destroyOnReturn: false })) {
console.log('first:', item); // first: header
break;
}
for await (const item of source) {
console.log('rest:', item); // rest: row1, rest: row2, rest: row3
}WHATWG ReadableStream in Node.js and Browsers
The web-standard ReadableStream is async iterable in Node.js 18 and later, in Deno, in Bun, and in current Chromium and Firefox releases. Browser support arrived later than in Node.js, so check your target browsers. Where it isn't available, fall back to stream.getReader() and a while loop over reader.read().
const stream = new ReadableStream({
start(controller) {
controller.enqueue('alpha');
controller.enqueue('beta');
controller.close();
}
});
for await (const chunk of stream) {
console.log(chunk); // alpha, beta
}The most common real source is a fetch() response body, which yields Uint8Array chunks. Piping it through TextDecoderStream turns those chunks into strings and handles multi-byte characters that are split across chunks:
const res = await fetch('https://example.com/');
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const text = res.body.pipeThrough(new TextDecoderStream());
let characters = 0;
for await (const piece of text) {
characters += piece.length;
}
console.log(`Received ${characters} characters`);Breaking out of the loop cancels the stream, which aborts the rest of the download. To keep the stream open after a break, iterate over stream.values({ preventCancel: true }).
Events as an Async Iterable
events.on() from node:events turns any EventEmitter into an async iterable. Each value is an array of the arguments the event was emitted with. The iterable never finishes on its own, so you end it with break, or pass an AbortSignal and stop it from outside:
import { EventEmitter, on } from 'node:events';
const emitter = new EventEmitter();
setTimeout(() => {
emitter.emit('job', 'resize', 1);
emitter.emit('job', 'upload', 2);
emitter.emit('job', 'stop', 3);
}, 10);
for await (const [name, id] of on(emitter, 'job')) {
console.log(id, name);
if (name === 'stop') break; // removes the listener
}
// 1 resize
// 2 upload
// 3 stopEvents that fire while your loop body is busy are queued without limit. Unlike a stream, an emitter can't be paused, so a fast emitter combined with a slow loop body grows memory. If an 'error' event is emitted on the same emitter, the loop throws.
Choosing a Source
- Bytes or text of any shape: iterate the stream directly. Set
encodingfor text, or decode withTextDecoderStreamfor web streams. - Line-oriented files or stdin: use
readlinewithcrlfDelay: Infinity, orfilehandle.readLines(). - Structured records: use a parser or driver that exposes an object-mode stream, then iterate it.
- Push-based notifications: use
events.on()with an exit condition or anAbortSignal. - Maximum throughput on huge inputs: measure first. Event listeners or
pipeline()with transform streams can be faster than readline's iterator.
Exercise
You run for await (const chunk of createReadStream('log.txt')) and call chunk.toString().split('\n') inside the loop to count lines. The count is sometimes higher than wc -l reports, and some lines look cut in half. Explain both symptoms and give a fix.
Show answer
Chunks are fixed-size pieces of bytes (64 KiB by default), so a line that crosses a chunk boundary is split into two pieces, and each piece is counted as a separate line. Without an encoding, a multi-byte UTF-8 character can also be split, which corrupts it when each Buffer is converted on its own. Fix it by wrapping the stream in readline.createInterface({ input, crlfDelay: Infinity }) and iterating lines, or by using filehandle.readLines().
Exercise
A script reads the first line of a CSV with for await (const line of rl) { header = line; break; } and then tries a second for await over the same rl to read the data rows. The second loop prints nothing. Why, and what are two ways to fix it?
Show answer
The break calls the iterator's return(), which closes the readline interface (and the input stream with it), so the second loop has nothing left to read. Fix 1: use one loop and handle the first line specially, for example with a boolean flag or a line counter. Fix 2: for a plain Node.js stream, iterate with stream.iterator({ destroyOnReturn: false }) in the first loop so the stream stays open (an experimental API), then continue with a second loop.
Exercise
Your loop body awaits a 50 ms database insert for each line of a 2 GB file read through readline. Will memory usage grow to roughly the size of the file? Explain using the pull model.
Show answer
No. for await...of only requests the next line after the loop body finishes. The underlying file stream reads ahead until its buffer reaches highWaterMark and then pauses, so only a bounded amount of data is in memory at any time. The run will be slow, because the inserts are sequential, but memory stays roughly flat.