Sub topic 10
Strings to Bytes and Back
This chapter assumes you already know how to create a Uint8Array and read its elements. It also assumes you know that JavaScript strings are sequences of UTF-16 code units. Binary formats and network protocols store text as bytes, so you need a reliable way to move between the two. Browsers, Node.js, and Deno all provide TextEncoder and TextDecoder for this.
The Working Model
TextEncoder always produces UTF-8. Its encode() method takes a string and returns a new Uint8Array. TextDecoder reverses the process: it takes an ArrayBuffer, a typed array, or a DataView and returns a string. Its default encoding is UTF-8, and it can also decode legacy encodings such as windows-1252 or utf-16le when you pass a label.
const bytes = new TextEncoder().encode('héllo');
console.log(bytes.length); // 6, because 'é' takes two bytes in UTF-8
const text = new TextDecoder().decode(bytes);
console.log(text); // "héllo"Common Error: Treating string length as byte length
string.length counts UTF-16 code units, not bytes. ASCII characters take one byte in UTF-8. Accented letters take two bytes, most other characters in the Basic Multilingual Plane take three, and emoji take four. If you size a buffer or write a length prefix from string.length, the result will be wrong as soon as the text contains non-ASCII characters.
const s = '😀';
console.log(s.length); // 2 (a surrogate pair)
console.log(new TextEncoder().encode(s).length); // 4Encoding into an Existing Buffer
encode() allocates a new array on every call. encodeInto() writes into a Uint8Array you already have and returns how many code units it read and how many bytes it wrote. It never writes a partial character, so it stops early when the destination is full.
const dest = new Uint8Array(4);
const result = new TextEncoder().encodeInto('héllo', dest);
console.log(result); // { read: 3, written: 4 }
console.log(Array.from(dest)); // [104, 195, 169, 108]For UTF-8, the worst case is three bytes per UTF-16 code unit, so a destination of str.length * 3 bytes is always large enough.
Invalid Bytes and Streaming
By default, TextDecoder replaces invalid byte sequences with U+FFFD (�) and does not report an error. Pass { fatal: true } when corrupt input should cause a failure.
const bad = new Uint8Array([0xff]);
console.log(new TextDecoder().decode(bad)); // "\uFFFD"
try {
new TextDecoder('utf-8', { fatal: true }).decode(bad);
} catch (e) {
console.log(e instanceof TypeError); // true
}Data that arrives in chunks can split a multi-byte character across two chunks. If you decode each chunk separately, both halves become U+FFFD. Pass { stream: true } on every chunk except the last, and the decoder keeps the incomplete bytes until the next call.
const dec = new TextDecoder();
let out = dec.decode(new Uint8Array([0x68, 0xc3]), { stream: true });
console.log(out); // "h"
out += dec.decode(new Uint8Array([0xa9]));
console.log(out); // "hé"Summary of Options
| API | Option | Effect |
|---|---|---|
| `TextEncoder.encode` | none | Returns a new UTF-8 `Uint8Array` |
| `TextEncoder.encodeInto` | none | Writes into an existing array and returns `{ read, written }` |
| `TextDecoder` constructor | `fatal: true` | Throws `TypeError` on invalid bytes |
| `TextDecoder` constructor | `ignoreBOM: true` | Keeps a leading BOM in the output |
| `TextDecoder.decode` | `stream: true` | Buffers incomplete characters for the next call |
Exercise
A protocol writes a one-byte length prefix and then the UTF-8 bytes of a string. For the string '€5', a developer writes '€5'.length as the prefix. What value do they write, what is the correct value, and how should they compute it?
Show answer
They write 2, because '€5' has two UTF-16 code units. The correct value is 4: '€' (U+20AC) encodes to three UTF-8 bytes and '5' to one. They should encode first and use the byte count: const bytes = new TextEncoder().encode('€5'); then write bytes.length.
Exercise
Why does decoding the chunks [0x68, 0xc3] and [0xa9] with two separate decode() calls, without the stream option, give "h\uFFFD\uFFFD" instead of "hé"?
Show answer
The bytes 0xc3 0xa9 together encode 'é'. Without { stream: true }, the first call treats the lone 0xc3 at the end as an incomplete sequence and replaces it with U+FFFD. The second call sees 0xa9 as a continuation byte with no lead byte and also replaces it with U+FFFD.