Sub topic 12
Decoding Text That Arrives in Chunks
Text from a network response, a file stream, or a WebSocket often arrives as a series of byte chunks instead of one complete buffer. The chunk boundaries come from buffer sizes and packet sizes, not from character boundaries. A boundary can land in the middle of a multi-byte UTF-8 character. If you decode each chunk on its own, that character is corrupted.
This chapter assumes you already know how UTF-8 uses one to four bytes per code point, how Uint8Array holds bytes, and how TextDecoder.decode behaves in its lenient and fatal modes. It also assumes you can use async/await and run code in a modern browser or in Node.js 18 or later.
Why Per-Chunk Decoding Breaks
The euro sign € is U+20AC. In UTF-8 it takes three bytes: 0xE2 0x82 0xAC. Suppose a stream delivers the first two bytes in one chunk and the last byte in the next chunk.
const chunks = [new Uint8Array([0xe2, 0x82]), new Uint8Array([0xac])];
// Wrong: each chunk is decoded as if it were complete
const naive = chunks.map((chunk) => new TextDecoder().decode(chunk)).join("");
console.log(naive); // "��"
console.log(naive.length); // 2
console.log(naive === "\uFFFD\uFFFD"); // trueThe first call sees a valid start of a three-byte sequence and then reaches the end of its input, so it emits one U+FFFD replacement character. The second call sees 0xAC, a continuation byte with no lead byte, and emits another U+FFFD. The euro sign is gone and two replacement characters take its place. Nothing throws, so the bug can go unnoticed until a user with non-ASCII text reports it.
Reusing one decoder does not fix this by itself. A plain decode(chunk) call treats its input as the whole stream and resets the decoder's state afterward.
The stream Option
TextDecoder.decode accepts a second argument, { stream: true }. With this option the decoder keeps any incomplete trailing sequence in an internal buffer and returns only the characters it could finish. The next call prepends the buffered bytes to the new input.
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); // "€"The final decoder.decode() call takes no arguments and no stream option. It tells the decoder the stream has ended. If bytes are still buffered at that point, the stream ended partway through a character. In lenient mode they become one U+FFFD. In fatal mode the call throws.
What the Decoder Remembers
A streaming UTF-8 decoder only has to remember a little state: up to three pending bytes and how many more it expects. This is why the stream option costs almost nothing. The decoder also remembers whether it has already seen the start of the stream, which matters for byte order mark (BOM) handling, covered below.
After the flushing call, the decoder resets and you can reuse it for a new, unrelated stream. Do not share one streaming decoder between two streams that are being read at the same time. Their partial sequences would mix together.
Strict Decoding Across Chunks
fatal: true works with streaming. An invalid sequence throws as soon as the decoder can tell it is invalid. A sequence that is only incomplete does not throw until the flush, because the next chunk might still complete it.
const strict = new TextDecoder("utf-8", { fatal: true });
// An incomplete sequence is fine while streaming
console.log(strict.decode(new Uint8Array([0xe2, 0x82]), { stream: true })); // ""
// But the stream ends without the third byte
try {
strict.decode();
} catch (err) {
console.log(err.name); // "TypeError"
}
// A byte that can never be valid UTF-8 throws immediately
const strict2 = new TextDecoder("utf-8", { fatal: true });
try {
strict2.decode(new Uint8Array([0x68, 0xff]), { stream: true });
} catch (err) {
console.log(err.name); // "TypeError"
}This difference affects error handling. If you validate uploads or protocol messages strictly, wrap the final flush in your try block as well. Otherwise truncated input passes validation.
The BOM and Streaming
A UTF-8 byte order mark is the three bytes 0xEF 0xBB 0xBF at the start of some files. By default (ignoreBOM: false), TextDecoder strips a leading BOM. It does this once per stream. A BOM that appears later in the stream is decoded as U+FEFF like any other character.
const decoder = new TextDecoder();
const first = decoder.decode(new Uint8Array([0xef, 0xbb]), { stream: true });
const rest = decoder.decode(new Uint8Array([0xbf, 0x68, 0x69]), { stream: true });
const end = decoder.decode();
console.log(JSON.stringify(first + rest + end)); // "\"hi\""The BOM is stripped even when it is split across chunks. If you decode chunks with separate non-streaming calls, a BOM split across a boundary turns into replacement characters. A BOM that falls entirely inside a later chunk gets stripped from the middle of your text. Pass ignoreBOM: true when you need the U+FEFF character kept in the output, for example when you write the decoded text back out byte for byte.
TextDecoderStream for Web Streams
When your bytes come from a ReadableStream, such as fetch response bodies or Blob.stream(), use TextDecoderStream. It is a TransformStream that wraps a streaming TextDecoder. It accepts Uint8Array chunks, emits strings, and flushes automatically when the input stream closes.
// Runs in modern browsers and in Node.js 18+
const source = new ReadableStream({
start(controller) {
controller.enqueue(new Uint8Array([0x68, 0xc3])); // "h" + first byte of "é"
controller.enqueue(new Uint8Array([0xa9, 0xe2, 0x82])); // rest of "é" + start of "€"
controller.enqueue(new Uint8Array([0xac])); // end of "€"
controller.close();
},
});
const textStream = source.pipeThrough(new TextDecoderStream());
let text = "";
for await (const piece of textStream) {
text += piece;
}
console.log(text); // "hé€"Async iteration over a ReadableStream works in Node.js and in recent browsers. Where it is missing, use a reader:
async function fetchText(url) {
const response = await fetch(url);
const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
let text = "";
while (true) {
const { value, done } = await reader.read();
if (done) break;
text += value;
}
return text;
}TextDecoderStream takes the same constructor arguments as TextDecoder: a label, fatal, and ignoreBOM. With fatal: true, an invalid or truncated stream errors the readable side, and the rejection reaches your read() call or for await loop.
Processing Lines as They Arrive
Decoding is only the first stage. Streamed text is often split into lines, and line boundaries do not line up with chunks either. A second transform can buffer the partial last line:
function lineSplitter() {
let pending = "";
return new TransformStream({
transform(chunk, controller) {
const lines = (pending + chunk).split("\n");
pending = lines.pop(); // last piece may be incomplete
for (const line of lines) controller.enqueue(line);
},
flush(controller) {
if (pending) controller.enqueue(pending);
},
});
}
const bytes = new TextEncoder().encode("first €\nsecond é\nthird");
const source = new ReadableStream({
start(controller) {
// Split at awkward positions on purpose
controller.enqueue(bytes.subarray(0, 7));
controller.enqueue(bytes.subarray(7, 15));
controller.enqueue(bytes.subarray(15));
controller.close();
},
});
for await (const line of source
.pipeThrough(new TextDecoderStream())
.pipeThrough(lineSplitter())) {
console.log(line); // "first €", "second é", "third"
}The order of the stages matters. The decoder handles byte boundaries and the splitter handles line boundaries. Splitting raw bytes on 0x0A also works for UTF-8, because that byte never appears inside a multi-byte sequence. Splitting at arbitrary byte offsets does not.
Chunked Text in Node.js
Node's classic streams deliver Buffer chunks, and calling chunk.toString() on each one has the same bug as per-chunk TextDecoder calls. Call setEncoding("utf8") on the stream instead. Node then decodes with an internal StringDecoder that carries partial sequences between chunks.
// Node.js
const { Readable } = require("node:stream");
const euro = Buffer.from("€", "utf8"); // <Buffer e2 82 ac>
const stream = Readable.from([euro.subarray(0, 2), euro.subarray(2)], {
objectMode: false,
});
stream.setEncoding("utf8");
let text = "";
stream.on("data", (piece) => (text += piece));
stream.on("end", () => console.log(text)); // "€"A streaming TextDecoder also works in Node because Buffer is a Uint8Array. For web streams in Node, such as the body returned by the global fetch, use TextDecoderStream exactly as in the browser.
Choosing a Strategy
You can also skip streaming decoding entirely. Collect all the bytes, join them into one array, and decode once. This is correct but holds the whole payload in memory, and you get no text until the last chunk arrives.
function concatBytes(chunks) {
const total = chunks.reduce((sum, c) => sum + c.length, 0);
const out = new Uint8Array(total);
let offset = 0;
for (const c of chunks) {
out.set(c, offset);
offset += c.length;
}
return out;
}
const chunks = [new Uint8Array([0xe2, 0x82]), new Uint8Array([0xac])];
console.log(new TextDecoder().decode(concatBytes(chunks))); // "€"| Approach | Correct across boundaries | Memory | Text available early | Typical use |
|---|---|---|---|---|
| `decode(chunk)` per chunk | No | Low | Yes | Never for multi-byte text |
| `decode(chunk, { stream: true })` plus flush | Yes | Low | Yes | Manual loops, WebSocket binary frames |
| `TextDecoderStream` | Yes | Low | Yes | `fetch` bodies, `Blob.stream()`, pipelines |
| `setEncoding("utf8")` | Yes | Low | Yes | Node classic streams |
| Concatenate, then decode once | Yes | Whole payload | No | Small payloads, simple code |
Prefer TextDecoderStream when you already have a ReadableStream. Use the stream option when chunks arrive through callbacks or events. Concatenate only when payloads are small and bounded.
Exercise
A loop calls decoder.decode(chunk, { stream: true }) for every chunk of a file, but the final flush is missing. The file ends with the bytes 0x61 0xE2 0x82, a truncated euro sign. What does the loop produce in lenient mode, and what changes if you add the flush?
Show answer
Without the flush the output ends in "a", and the two buffered bytes are silently dropped, so nothing signals the truncation. With the final decoder.decode() call, the buffered bytes become one U+FFFD, giving "a\uFFFD". In fatal mode the same flush throws a TypeError.
Exercise
Why does decoding each chunk with new TextDecoder().decode(chunk) produce "\uFFFD\uFFFD" for the chunks [0xE2, 0x82] and [0xAC], instead of one replacement character or the euro sign?
Show answer
Each call treats its input as a complete stream. The first call finds a valid three-byte prefix cut off at the end of its input and emits one U+FFFD. The second call finds a continuation byte with no lead byte and emits a second U+FFFD. Neither call can see the other chunk.
Exercise
You pipe a fetch body through a line splitter and then through TextDecoderStream, with the splitter working on raw bytes by cutting at fixed 1024-byte offsets. Some lines contain garbled characters. What is wrong, and how do you fix it?
Show answer
Cutting at fixed byte offsets can split multi-byte UTF-8 sequences, and the cut pieces no longer line up with lines either. Decode first with TextDecoderStream, then split the resulting strings on "\n" while buffering the incomplete last line. Splitting raw bytes is only safe at 0x0A, which never occurs inside a multi-byte sequence.