Sub topic 5
Decoding Bytes with TextDecoder
This chapter turns bytes back into strings. It assumes you already know that JavaScript strings are UTF-16 code units, that UTF-8 encodes each code point as one to four bytes, and that Uint8Array is a view over an ArrayBuffer. You should also have used TextEncoder.encode and be able to run code in a browser console or Node.js.
TextDecoder is the reverse of TextEncoder, but the two are not symmetric. Any well-formed string can be encoded, while many byte sequences are not valid UTF-8. Most of what you need to know about TextDecoder comes down to what happens when the bytes are wrong.
The Basic Model
A TextDecoder is an object configured with an encoding and two options. Its decode method takes bytes and returns a string.
const bytes = new Uint8Array([0x68, 0xc3, 0xa9, 0x6c, 0x6c, 0x6f]);
const decoder = new TextDecoder();
console.log(decoder.encoding); // "utf-8"
console.log(decoder.fatal); // false
console.log(decoder.ignoreBOM); // false
console.log(decoder.decode(bytes)); // "héllo"The constructor signature is new TextDecoder(label, options):
| Parameter | Default | Effect |
|---|---|---|
| `label` | `"utf-8"` | Names the encoding of the input bytes |
| `options.fatal` | `false` | Throw a `TypeError` on malformed input instead of substituting U+FFFD |
| `options.ignoreBOM` | `false` | Keep a leading byte order mark in the output instead of stripping it |
All three settings are read-only properties on the instance. You can reuse one decoder for many calls. Without the stream option, each call to decode is independent and keeps no state between calls.
decode accepts an ArrayBuffer, any typed array (including Node's Buffer), or a DataView. Calling decode() with no argument returns an empty string.
Encoding Labels
TextEncoder only produces UTF-8. TextDecoder can read many legacy encodings defined by the WHATWG Encoding Standard. You choose one with a label, which is a case-insensitive name with surrounding whitespace ignored. Several labels can map to the same canonical encoding, and the encoding property reports the canonical name.
for (const label of ["UTF8", " utf-8 ", "latin1", "ascii", "utf-16"]) {
console.log(JSON.stringify(label), "->", new TextDecoder(label).encoding);
}
// "UTF8" -> utf-8
// " utf-8 " -> utf-8
// "latin1" -> windows-1252
// "ascii" -> windows-1252
// "utf-16" -> utf-16le
try {
new TextDecoder("utf-9");
} catch (err) {
console.log(err.name); // "RangeError"
}An unknown label throws a RangeError at construction time. It does not fail when you later call decode. If the label comes from outside your code, such as an HTTP Content-Type charset, wrap the constructor in try/catch and fall back to UTF-8.
const legacy = new Uint8Array([0x80, 0xe9]);
console.log(new TextDecoder("latin1").decode(legacy)); // "ێ"In Node.js, encodings other than UTF-8 and UTF-16LE need ICU data. Official Node builds ship with full ICU. A custom build compiled with small-icu or without ICU throws a RangeError for labels like "shift_jis".
Lenient Mode and the Replacement Character
By default fatal is false. The decoder then never throws on bad data. Each malformed sequence becomes U+FFFD REPLACEMENT CHARACTER (�), and decoding continues with the next byte.
The number of replacement characters is fixed by the standard. A sequence that starts correctly but is cut off or broken produces one U+FFFD for the valid prefix. A byte that can never begin or continue a sequence produces its own U+FFFD. The helper below prints code points so you can see the output exactly.
const decoder = new TextDecoder();
const show = (arr) =>
[...decoder.decode(new Uint8Array(arr))]
.map((c) => c.codePointAt(0).toString(16).toUpperCase().padStart(4, "0"))
.join(" ");
console.log(show([0xe2, 0x82, 0xac])); // "20AC" valid €
console.log(show([0xe2, 0x82, 0x41])); // "FFFD 0041" truncated € followed by "A"
console.log(show([0xe2, 0x82])); // "FFFD" truncated at end of input
console.log(show([0xc0, 0x80])); // "FFFD FFFD" overlong encoding, both bytes invalid
console.log(show([0xed, 0xa0, 0x80])); // "FFFD FFFD FFFD" encoded surrogate, rejected
console.log(show([0x68, 0xff, 0x69])); // "0068 FFFD 0069" 0xFF never appears in UTF-8These rules give the same output in every engine, so lenient decoding is predictable. It is also lossy, and the loss cannot be undone:
const original = new Uint8Array([0xff]);
const text = new TextDecoder().decode(original);
const back = new TextEncoder().encode(text);
console.log(back); // Uint8Array(3) [239, 191, 189] — not [255]Lenient mode fits display. Showing a user a log file or a web page with a few � characters is usually better than showing nothing.
Fatal Mode
With fatal: true, the first malformed sequence makes decode throw a TypeError. Use it when invalid input means something is wrong: a protocol requires UTF-8, you are checking an upload, or silent corruption would cause a bug later.
function decodeStrict(bytes) {
const decoder = new TextDecoder("utf-8", { fatal: true });
try {
return { ok: true, text: decoder.decode(bytes) };
} catch (err) {
if (err instanceof TypeError) {
return { ok: false, error: err.message };
}
throw err;
}
}
console.log(decodeStrict(new Uint8Array([0x68, 0x69])));
// { ok: true, text: "hi" }
console.log(decodeStrict(new Uint8Array([0x68, 0xff])).ok);
// falseThe error message is not standardized. Node sets err.code to "ERR_ENCODING_INVALID_ENCODED_DATA", but browsers have no such code. Check instanceof TypeError rather than matching message text.
Fatal mode also works as a cheap UTF-8 validator. If decode returns without throwing, the bytes were valid UTF-8.
Byte Order Marks
A byte order mark (BOM) is the code point U+FEFF placed at the very start of a text. In UTF-8 it is the bytes EF BB BF. Windows tools often write it, and it causes subtle bugs: a CSV header that looks like "id" is really "\uFEFFid", so a lookup by "id" fails.
TextDecoder strips one leading BOM that matches the decoder's encoding by default. Set ignoreBOM: true to keep it.
const withBom = new Uint8Array([0xef, 0xbb, 0xbf, 0x69, 0x64]);
const stripped = new TextDecoder().decode(withBom);
const kept = new TextDecoder("utf-8", { ignoreBOM: true }).decode(withBom);
console.log(stripped === "id"); // true
console.log(kept === "\uFEFFid"); // true
console.log(kept.length); // 3Some details are easy to get wrong:
- Only a BOM at offset 0 is stripped. A U+FEFF in the middle of the text is kept as an ordinary character.
- Only one BOM is stripped. Two leading BOMs leave one in the output.
- The name
ignoreBOMreads backwards.truemeans "do not treat the BOM specially", which keeps it in the output. - The BOM does not switch the encoding. A UTF-16LE BOM fed to a UTF-8 decoder becomes two U+FFFD characters.
Decoding Views, Not Buffers
Most TextDecoder bugs in real code come from passing the wrong range of bytes. When you pass a typed array, the decoder reads only the bytes that view covers. When you pass view.buffer, it reads the entire underlying ArrayBuffer.
const buffer = new ArrayBuffer(11);
new Uint8Array(buffer).set(new TextEncoder().encode("header:body"));
const body = new Uint8Array(buffer, 7); // view starting at byte 7
const decoder = new TextDecoder();
console.log(decoder.decode(body)); // "body"
console.log(decoder.decode(body.buffer)); // "header:body"
const view = new DataView(buffer, 0, 6);
console.log(decoder.decode(view)); // "header"The same mistake happens in Node. Buffer.from and Buffer.alloc often allocate small buffers from a shared memory pool, so buf.buffer can contain unrelated data from other buffers. Pass the Buffer itself, which is a Uint8Array, and never its .buffer.
Chunk Boundaries
Each plain decode call treats its input as complete. If a multi-byte character is split between two network chunks, decoding each chunk separately produces U+FFFD at the split:
const decoder = new TextDecoder();
const part1 = decoder.decode(new Uint8Array([0xe2, 0x82]));
const part2 = decoder.decode(new Uint8Array([0xac]));
console.log(part1 + part2 === "\uFFFD\uFFFD"); // true, not "€"The stream option fixes this, and the chapter "Decoding Text That Arrives in Chunks" covers it. For now, remember that concatenating separately decoded chunks is a bug whenever chunk boundaries come from the network or the file system.
Common Errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `RangeError` when constructing | Unknown or misspelled label | Validate or default the label |
| Extra text from other data in output | Passed `view.buffer` instead of the view | Pass the typed array itself |
| Occasional `�` in long streamed text | Chunks decoded independently | Use `{ stream: true }` |
| `"€"` where you expected U+0080 | `"latin1"` means windows-1252 | Do not use TextDecoder for binary strings |
| Header key lookup fails on first column | BOM kept or written by another tool | Keep default `ignoreBOM: false` |
| Binary data corrupted after round trip | Non-UTF-8 bytes decoded as text | Use base64 for binary |
| Bad input passes silently | Default lenient mode | Use `{ fatal: true }` |
Exercise
What does new TextDecoder().decode(new Uint8Array([0x61, 0xe2, 0x82, 0x62])) return, and what happens if the decoder is created with { fatal: true }?
Show answer
Lenient mode returns "a\uFFFDb". The bytes E2 82 begin a three-byte sequence, but 0x62 is not a continuation byte, so the truncated prefix becomes one U+FFFD and decoding resumes at 0x62. With fatal: true, decode throws a TypeError and returns nothing.
Exercise
A function receives a Node Buffer called buf containing a UTF-8 JSON payload and calls JSON.parse(new TextDecoder().decode(buf.buffer)). It works in tests but sometimes fails in production with a syntax error. Why, and what is the fix?
Show answer
buf.buffer is the whole underlying ArrayBuffer. Small Buffers are often slices of a shared pool, so the decoder also reads bytes belonging to other buffers, which corrupts the JSON. Pass the view itself with new TextDecoder().decode(buf), or build new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength).
Exercise
You decode a user-uploaded CSV with new TextDecoder("utf-8", { ignoreBOM: true }) and find that row[0]["id"] is undefined even though the header shows "id". Explain and fix.
Show answer
The file starts with a UTF-8 BOM (EF BB BF). Setting ignoreBOM: true keeps it, so the first header is "\uFEFFid". Remove the option so the default (false) strips the leading BOM, or strip it with text.replace(/^\uFEFF/, "").