Sub topic 10
Async Iterables You Already Have: Streams and readline
This chapter assumes you know for await...of, the early-exit behavior covered in the previous chapter (break calls return()), and how to run ES modules in Node.js 18 or later. Every example uses top-level await, so save each one as a .mjs file.
You rarely need to build an async iterable yourself. Node.js readable streams, readline interfaces, and web ReadableStream objects all implement Symbol.asyncIterator. That means you can read them with for await...of and skip event listeners entirely.
Node.js Readable Streams
Every stream.Readable is async iterable. Each iteration gives you one chunk. File streams produce Buffer chunks of up to 64 KiB by default. If you call setEncoding(), the chunks come out as strings instead.
import { createReadStream } from 'node:fs';
import { writeFile } from 'node:fs/promises';
await writeFile('data.txt', 'alpha\nbeta\ngamma\n');
const stream = createReadStream('data.txt');
stream.setEncoding('utf8');
let text = '';
for await (const chunk of stream) {
text += chunk;
}
console.log(text.length); // 17The loop respects backpressure, meaning the stream only reads more data when the consumer is ready for it. The stream reads the next chunk only after your loop body finishes, so a slow body never piles up unread data in memory.
A chunk boundary has nothing to do with line boundaries. If you need lines, use readline.
Reading Lines with readline
A readline Interface built on top of a stream yields one line per iteration, with the line ending removed. Setting crlfDelay: Infinity makes it treat \r\n as a single line break.
import { createReadStream } from 'node:fs';
import { createInterface } from 'node:readline';
const rl = createInterface({
input: createReadStream('data.txt'),
crlfDelay: Infinity
});
let lineCount = 0;
for await (const line of rl) {
lineCount++;
console.log(`${lineCount}: ${line}`);
}
console.log(`Lines: ${lineCount}`);Web ReadableStream
fetch() response bodies are web ReadableStream objects. Node.js 18 and later lets you iterate them directly, and so do recent versions of most browsers. Check your target browsers before you rely on it. Raw chunks arrive as Uint8Array. Piping the stream through TextDecoderStream turns them into text.
const res = await fetch('https://example.com/');
const textStream = res.body.pipeThrough(new TextDecoderStream());
let total = 0;
for await (const chunk of textStream) {
total += chunk.length;
}
console.log(`Received ${total} characters`);What Early Exit Does to Each Source
Breaking out of the loop calls the iterator's return(), and each source responds by releasing its resources:
| Source | Value per iteration | Effect of `break` or a thrown error |
|---|---|---|
| Node.js `Readable` | `Buffer` or string chunk | Stream is destroyed and the file handle is closed |
| `readline` `Interface` | One line, without its line ending | Interface is closed |
| Web `ReadableStream` | Chunk, often `Uint8Array` | Stream is cancelled, unless you iterate `stream.values({ preventCancel: true })` |
This cleanup is the main advantage over on('data') listeners. You don't need to call destroy() yourself, and an error thrown in the loop body can't leave a file descriptor open.
Exercise
You want the first line of a large log file that starts with "ERROR", and you want the file closed as soon as you find it. Write the loop and explain why the file is not left open.
Show answer
Build a readline interface over createReadStream(path) with crlfDelay: Infinity, then run for await (const line of rl) { if (line.startsWith('ERROR')) { found = line; break; } }. The break calls the iterator's return(), which closes the readline interface and destroys the underlying file stream, so the file handle is released without a manual destroy() call.
Exercise
A Node.js stream loop prints chunks, but some words appear split across two iterations. Why does this happen, and how do you fix it?
Show answer
Stream chunks are fixed-size pieces of bytes, so a chunk boundary can land in the middle of a word or line. Iterate a readline interface to get whole lines, or collect the chunks and split the result yourself.