Sub topic 10
Strings to Bytes and Back
Binary formats seldom contain only numbers. File headers hold magic strings, network protocols carry names and messages, and JSON arrives as bytes before it becomes text. This chapter shows how to move between JavaScript strings and raw bytes with TextEncoder and TextDecoder, and covers the edge cases that cause subtle bugs.
The chapter assumes you already know how typed arrays view an ArrayBuffer, how subarray differs from slice, and how DataView reads values at byte offsets. It also assumes you know that a byte holds values 0 to 255.
Why Strings Need Encoding
A JavaScript string is a sequence of UTF-16 code units. A code unit is a 16-bit value. Most common characters take one code unit, and characters outside the Basic Multilingual Plane, such as most emoji, take two. Those two units are called a surrogate pair. A string's length counts code units. It does not count characters, and it does not count bytes.
Bytes on disk and on the network are almost always UTF-8. UTF-8 is a variable-width encoding that uses 1 to 4 bytes per character:
| Character range | Example | UTF-16 code units | UTF-8 bytes |
|---|---|---|---|
| U+0000 to U+007F (ASCII) | `h` | 1 | 1 |
| U+0080 to U+07FF | `é` | 1 | 2 |
| U+0800 to U+FFFF | `€` | 1 | 3 |
| U+10000 to U+10FFFF | `😀` | 2 | 4 |
The browser and Node.js both provide TextEncoder and TextDecoder as globals, so you never need to work out these bit patterns by hand.
Encoding with TextEncoder
TextEncoder always produces UTF-8. Its constructor takes no encoding argument, and its encoding property is always "utf-8". The encode method returns a new Uint8Array backed by a fresh ArrayBuffer.
const encoder = new TextEncoder();
console.log(encoder.encoding); // "utf-8"
const bytes = encoder.encode('héllo');
console.log(bytes.length); // 6, because 'é' takes two bytes in UTF-8
console.log(bytes); // Uint8Array [104, 195, 169, 108, 108, 111]
const emoji = '😀';
console.log(emoji.length); // 2 (code units)
console.log([...emoji].length); // 1 (code point)
console.log(encoder.encode(emoji).length); // 4 (bytes)Treat these three counts as separate numbers. If a protocol has a length-prefixed string field, the prefix holds the byte count, so you must encode the string first and then measure the result.
Writing into an existing buffer with encodeInto
encode allocates a new array on every call. When you are filling a larger buffer, such as a message you are assembling, encodeInto(string, uint8array) writes directly into memory you already have. It returns an object with two counts. read is the number of UTF-16 code units consumed, and written is the number of bytes produced.
const encoder = new TextEncoder();
const target = new Uint8Array(4);
const result = encoder.encodeInto('héllo', target);
console.log(result); // { read: 3, written: 4 }
console.log(target); // Uint8Array [104, 195, 169, 108]The encoder stopped after "hél" because the next character would not fit. It never writes a partial character. If read is less than the string's length, the string was truncated, and you must decide whether that counts as an error.
To guarantee that a string fits, allocate string.length * 3 bytes. No UTF-16 code unit needs more than 3 UTF-8 bytes. A surrogate pair uses 2 units and produces 4 bytes, so it stays under the limit.
Lone surrogates
A string can contain an unpaired surrogate, such as '\uD800'. That is valid in JavaScript and invalid in UTF-8. TextEncoder replaces each lone surrogate with U+FFFD, the replacement character, which encodes as EF BF BD. No error is raised, so the data changes silently.
const encoder = new TextEncoder();
console.log(encoder.encode('\uD800')); // Uint8Array [239, 191, 189]
console.log('\uD800'.isWellFormed()); // false (ES2024)
console.log('\uD800'.toWellFormed() === '\uFFFD'); // trueIf round-trip fidelity matters, for example when you store user-supplied keys, check isWellFormed() before encoding and reject the input when it returns false.
Decoding with TextDecoder
TextDecoder turns bytes back into a string. Its decode method accepts an ArrayBuffer, any typed array, or a DataView. For a view, it decodes only the bytes the view covers, which lets you decode a field in place without copying it.
const decoder = new TextDecoder(); // defaults to "utf-8"
const bytes = new Uint8Array([0x4d, 0x41, 0x47, 0x49, 0x43, 0x00, 0x00, 0x00]);
console.log(decoder.decode(bytes.subarray(0, 5))); // "MAGIC"
console.log(decoder.decode(new DataView(bytes.buffer, 1, 3))); // "AGI"Many formats store strings in fixed-width fields padded with zero bytes. TextDecoder does not stop at a zero byte. It decodes the zeros as U+0000 characters, so find the terminator yourself:
function readFixedString(bytes, offset, width) {
const field = bytes.subarray(offset, offset + width);
const end = field.indexOf(0);
return new TextDecoder().decode(end === -1 ? field : field.subarray(0, end));
}
const header = new Uint8Array([0x4d, 0x41, 0x47, 0x49, 0x43, 0x00, 0x00, 0x00]);
console.log(readFixedString(header, 0, 8)); // "MAGIC", not "MAGIC\u0000\u0000\u0000"Invalid bytes and the fatal option
By default, the decoder replaces malformed sequences with U+FFFD and continues. That suits display text and is dangerous for validation. With { fatal: true }, the decoder throws a TypeError instead.
const bad = new Uint8Array([0x68, 0xff, 0x69]); // 0xff never appears in UTF-8
console.log(new TextDecoder().decode(bad)); // "h\uFFFDi"
try {
new TextDecoder('utf-8', { fatal: true }).decode(bad);
} catch (e) {
console.log(e instanceof TypeError); // true
}Use fatal: true when bad input should be rejected, such as checking that an upload is valid UTF-8 or decoding protocol identifiers that are later compared for equality.
The byte order mark
Some files start with a UTF-8 byte order mark (BOM), the bytes EF BB BF. The decoder strips it by default. Set ignoreBOM: true to keep it as U+FEFF in the output, which you may need if you are re-emitting the file byte for byte.
const withBom = new Uint8Array([0xef, 0xbb, 0xbf, 0x68, 0x69]);
console.log(new TextDecoder().decode(withBom).length); // 2, "hi"
console.log(new TextDecoder('utf-8', { ignoreBOM: true }).decode(withBom).length); // 3Streaming: characters split across chunks
Data from a network stream or file reader arrives in chunks, and a multi-byte character can be split across a chunk boundary. If you decode each chunk on its own, both halves turn into replacement characters. Pass { stream: true } so the decoder keeps the incomplete trailing bytes until the next call. Then make one final call without the option to flush anything left over.
// 'é' is C3 A9, split across two chunks
const chunk1 = new Uint8Array([0x68, 0xc3]);
const chunk2 = new Uint8Array([0xa9]);
const naive = new TextDecoder();
console.log(naive.decode(chunk1) + naive.decode(chunk2)); // "h\uFFFD\uFFFD"
const streaming = new TextDecoder();
let text = streaming.decode(chunk1, { stream: true }); // "h"
text += streaming.decode(chunk2, { stream: true }); // "é"
text += streaming.decode(); // flush, ""
console.log(text); // "hé"For web streams there is also TextDecoderStream, which applies the same logic inside a pipe: response.body.pipeThrough(new TextDecoderStream()).
Decoding other encodings
Encoding is UTF-8 only, but decoding supports the encodings in the WHATWG Encoding Standard. Pass a label to the constructor. Labels are normalized, so "latin1" maps to "windows-1252", and an unknown label throws a RangeError.
const utf16 = new Uint8Array([0x68, 0x00, 0x69, 0x00]);
console.log(new TextDecoder('utf-16le').decode(utf16)); // "hi"
console.log(new TextDecoder('latin1').encoding); // "windows-1252"
console.log(new TextDecoder('windows-1252').decode(new Uint8Array([0x80]))); // "€"Node.js builds with small ICU support only a few encodings. The official binaries ship full ICU and support all of them.
Putting It Together: a Length-Prefixed String
This pair of helpers writes a string as a 16-bit big-endian byte count followed by UTF-8 bytes, then reads it back. It combines encodeInto, DataView, and in-place decoding.
const encoder = new TextEncoder();
const decoder = new TextDecoder('utf-8', { fatal: true });
function writeString(buffer, offset, str) {
const bytes = new Uint8Array(buffer);
const { read, written } = encoder.encodeInto(str, bytes.subarray(offset + 2));
if (read < str.length) throw new RangeError('string does not fit');
if (written > 0xffff) throw new RangeError('string too long for uint16 prefix');
new DataView(buffer).setUint16(offset, written);
return offset + 2 + written; // next free offset
}
function readString(buffer, offset) {
const len = new DataView(buffer).getUint16(offset);
const text = decoder.decode(new Uint8Array(buffer, offset + 2, len));
return { text, next: offset + 2 + len };
}
const buf = new ArrayBuffer(64);
let pos = writeString(buf, 0, 'héllo');
pos = writeString(buf, pos, '😀');
console.log(pos); // 15 (2 + 6 + 2 + 4 + 1? no: 2 + 6 + 2 + 4 = 14)The last comment is deliberately wrong, so check it against the actual output. Run the code and you will see 14. The fields are 2 prefix bytes plus 6 bytes for "héllo", then 2 prefix bytes plus 4 bytes for the emoji. Reading back works the same way:
const first = readString(buf, 0);
const second = readString(buf, first.next);
console.log(first.text, second.text, second.next); // "héllo" "😀" 14Common Mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Using `str.length` as a byte count | Truncated or overlapping fields | Use `encode(str).length` or `encodeInto(...).written` |
| Decoding chunks independently | U+FFFD at chunk boundaries | Use `{ stream: true }` and a final flush |
| Decoding zero-padded fields whole | Trailing `\u0000` characters break comparisons | Cut the view at `indexOf(0)` |
| Trusting default decoding for validation | Corrupt input accepted silently | Use `{ fatal: true }` |
| Building strings with `String.fromCharCode(...bytes)` | Wrong output for any non-ASCII byte, and stack errors on large arrays | Use `TextDecoder` |
Exercise
A buffer contains the bytes [0xE2, 0x82, 0xAC, 0x31] (the euro sign followed by "1"). It arrives in two chunks, [0xE2, 0x82] and [0xAC, 0x31]. What does decoding each chunk with a fresh, non-streaming TextDecoder and concatenating the results produce, and what changes with { stream: true }?
Show answer
Without streaming, the first chunk is an incomplete sequence, so it becomes one U+FFFD. The second chunk starts with a continuation byte that has no lead byte, so it becomes another U+FFFD followed by "1". The result is "\uFFFD\uFFFD1". With one decoder and { stream: true }, the first call returns "" and holds E2 82, and the second call returns "€1". A final decode() call returns "".
Exercise
You need a Uint8Array large enough that encoder.encodeInto(s, target) never truncates any string s. What size do you allocate, and why is that enough even for emoji?
Show answer
Allocate s.length * 3 bytes. Each UTF-16 code unit encodes to at most 3 UTF-8 bytes. A character outside the BMP uses two code units, giving a budget of 6 bytes, and it needs only 4. Lone surrogates become U+FFFD, which takes 3 bytes, so they also stay within the limit.
Exercise
Why does new TextEncoder().encode('\uD83D') followed by new TextDecoder().decode(...) not give back the original string, and how could you detect this before encoding?
Show answer
'\uD83D' is a lone high surrogate, which has no UTF-8 representation. TextEncoder replaces it with U+FFFD (bytes EF BF BD), so decoding returns "\uFFFD". Calling '\uD83D'.isWellFormed() returns false, which lets you reject or repair the string before encoding.