Web Streams move data asynchronously in chunks. A ReadableStream can enqueue values for readers; consuming a fetched response with for await...of processes chunks as they arrive. For text, TextDecoder’s streaming mode preserves partial characters between chunks. section 11.2.1 section 11.2.1
Listing 11.4 Decoding a text stream one chunk at a time
import assert from "node:assert";
import { once } from "node:events";
import { createServer } from "node:http";
import { setTimeout } from "node:timers/promises";
const words = [
"One ",
"word ",
"at ",
"a ",
"time.",
];
const server = createServer(async (req, res) => {
for (const word of words) { #A
res.write(word); #A
await setTimeout(100); #A
} #A
res.end();
});
server.listen(4567);
await once(server, "listening");
const res = await fetch("http://localhost:4567"); #B
assert( #C
res.body !== null, #C
"The response must have a body", #C
); #C
const resStrings: string[] = []; #D
const decoder = new TextDecoder(); #D
for await (const chunk of res.body) { #D
resStrings.push( #D
decoder.decode(chunk, { stream: true }), #D
); #D
process.stdout.write(text); #D
} #D
process.stdout.write("\n"); #D
console.assert(
resStrings.join("") === "One word at a time.",
"All chunks together form the complete message",
);
server.close();
See a server send text in delayed chunks and a client decode the fetched response as a stream. section 11.2.1
Listing 11.5 Creating a ReadableStream
import { setTimeout } from "node:timers/promises";
const ninjas = [
"Leonardo",
"Donatello",
"Raphael",
"Michelangelo",
];
const source = new ReadableStream<string>({
async start(controller) { #A
for (const ninja of ninjas) { #A
controller.enqueue(ninja); #A
await setTimeout(100); #A
} #A
controller.close(); #A
},
});
const received: string[] = []; #B
for await (const ninja of source) { #B
received.push(ninja); #B
} #B
console.assert(
received.length === 4,
"Four ninjas were received",
);
See a custom ReadableStream enqueue values, close, and deliver them to an async iterator. section 11.2.1

