Sub topic 12
Decoding Text That Arrives in Chunks
This chapter assumes you know how TextDecoder.decode turns a Uint8Array into a string, and that UTF-8 uses one to four bytes per code point. You should also be able to run async code in a browser console or Node.js 18 or later.
Why chunk boundaries break naive decoding
Network responses, file reads, and sockets rarely deliver data in one piece. They deliver chunks of bytes, and those chunk boundaries follow buffer sizes, not character boundaries. A multi-byte character such as € (bytes E2 82 AC) can be split, with two bytes at the end of one chunk and the last byte at the start of the next.
If you decode each chunk on its own, the decoder sees an incomplete sequence at the end of the first chunk and a stray continuation byte at the start of the second. Each one becomes U+FFFD:
const chunks = [new Uint8Array([0xe2, 0x82]), new Uint8Array([0xac])];
let broken = "";
for (const chunk of chunks) {
broken += new TextDecoder().decode(chunk); // each chunk decoded in isolation
}
console.log(broken === "\uFFFD\uFFFD"); // true: the € is lostThis bug is easy to miss. Tests with ASCII-only data pass, and corruption shows up only when a non-ASCII character happens to land on a boundary.
The stream option
Pass { stream: true } to tell one decoder that more bytes are coming. Any incomplete sequence at the end of a chunk is held back and joined with the next chunk. When the input ends, call decode() with no arguments to flush.
const decoder = new TextDecoder();
const chunks = [new Uint8Array([0xe2, 0x82]), new Uint8Array([0xac])];
let text = "";
for (const chunk of chunks) {
text += decoder.decode(chunk, { stream: true });
}
text += decoder.decode(); // flush any buffered bytes
console.log(text); // "€"Three rules matter here:
| Rule | What goes wrong if you break it |
|---|---|
| Use one decoder instance for the whole stream | A new decoder per chunk has no buffered bytes, so you get the bug shown above |
| Call `decode()` with no arguments at the end | A truncated final character is silently dropped instead of reported |
| Reuse a decoder only after flushing | Bytes left over from the previous stream leak into the next one |
TextDecoderStream
When your bytes already arrive as a ReadableStream, such as response.body from fetch, use TextDecoderStream. It is a transform stream that wraps a streaming TextDecoder, so it handles buffering and flushing for you.
async function main() {
const bytes = new TextEncoder().encode("héllo €"); // 10 bytes
const source = new ReadableStream({
start(controller) {
controller.enqueue(bytes.subarray(0, 8)); // splits the € after its first byte
controller.enqueue(bytes.subarray(8));
controller.close();
},
});
const reader = source.pipeThrough(new TextDecoderStream()).getReader();
let text = "";
while (true) {
const { done, value } = await reader.read();
if (done) break;
text += value; // value is already a string
}
console.log(text); // "héllo €"
}
main();With fetch, the same pattern is response.body.pipeThrough(new TextDecoderStream()). The constructor accepts the same label and { fatal } options as TextDecoder. Use the manual stream: true loop when your chunks come from a callback API, such as Node's data events, and not from a web stream.
Exercise
A WebSocket handler receives binary UTF-8 frames and runs log += new TextDecoder().decode(frame) for each one. Users report occasional "�" characters in non-English messages. What is the cause, and how do you fix it?
Show answer
Each frame gets a fresh decoder, so a multi-byte character split across two frames is decoded as two invalid fragments, and each becomes U+FFFD. Create one TextDecoder outside the handler, call decoder.decode(frame, { stream: true }) for each frame, and call decoder.decode() once when the connection closes to flush any remaining bytes.
Exercise
You decode a stream with { stream: true } but forget the final decode() call, and the last chunk ends with the bytes F0 9F. What appears at the end of your text?
Show answer
Nothing appears. The two bytes stay buffered inside the decoder and are never emitted, so the truncation passes silently. Calling decode() at the end would emit U+FFFD, or throw a TypeError if the decoder was created with fatal: true.