TextDecoder Streams Decode Multibyte Chunks
Decoding a payload split inside a multibyte character needs stream: true; one-shot decodes turn the torn prefix into replacement characters instead.
Code
// Pick a split point that lands inside a multibyte sequence.
const text = "café \u{1F680}"; // é is 2 bytes, the rocket is 4 in UTF-8
const bytes = new TextEncoder().encode(text);
console.log("chars:", [...text].length, "bytes:", bytes.length);
// byte 4 falls inside é (bytes 3-4): the boundary is mid-codepoint
const mid = bytes.slice(0, 4);
const rest = bytes.slice(4);
const decoder = new TextDecoder();
const streamed = decoder.decode(mid, { stream: true }) + decoder.decode(rest);
console.log("streamed ok:", streamed === text);
// one-shot decode of the broken prefix: trailing replacement character
console.log("broken prefix:", JSON.stringify(new TextDecoder().decode(mid)));
// fatal mode turns the same broken bytes into a TypeError
try {
new TextDecoder("utf-8", { fatal: true }).decode(mid);
} catch (error) {
console.log("fatal:", (error as TypeError).name);
}Output
Captured from a sandboxed run of this snippet in the build pipeline.
chars: 6 bytes: 10
streamed ok: true
broken prefix: "caf�"
fatal: TypeErrorHow it works
Module-level bindings hold the data — text, bytes, mid, rest — with no function scope in between.
Watch out for
- Every symbol it touches is a language built-in — nothing to fetch.
Using it
Expect labeled output — chars:, streamed ok:, broken prefix: — when the file runs.
Key statements
const text = "café \u{1F680}"; // é is 2 bytes, the rocket is 4 in UTF-8
const bytes = new TextEncoder().encode(text);
const streamed = decoder.decode(mid, { stream: true }) + decoder.decode(rest);
new TextDecoder("utf-8", { fatal: true }).decode(mid);
Interactive Tools for This Topic
FAQ
- Does the code pull in any external packages?
- No external packages are involved; every call resolves to a built-in API. Its state lives in module-level bindings: `text`, `bytes`, `mid`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.