WHATWG, also called Web Standards, defines web platform features such as fetch, TextDecoder, and the Web Streams APIs. These specifications sit alongside ECMAScript, which defines JavaScript as a language; Node.js has adopted WHATWG features, making them available across major JavaScript runtimes. section 11.2.1
Decoding streamed text
A network stream can split a multibyte UTF-8 character across chunks. TextDecoder.decode(chunk, { stream: true }) preserves partial characters between calls, avoiding corrupted text. 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",
);
A ReadableStream example enqueues values from a start method and reads them with for await…of. section 11.2.1
