Sub topic 2
Decoding Bytes with TextDecoder
This chapter assumes you know how TextEncoder turns strings into UTF-8 bytes in a Uint8Array, and that you can run code in a browser console or Node.js.
Decoding Bytes with TextDecoder
TextDecoder converts bytes back into a string. It decodes UTF-8 by default. When it meets malformed bytes, it replaces them with U+FFFD (�) and keeps going. If you pass fatal: true, it throws a TypeError instead.
const bytes = new Uint8Array([0x68, 0xff]);
console.log(new TextDecoder().decode(bytes)); // "h\uFFFD"
const strict = new TextDecoder("utf-8", { fatal: true });
try {
strict.decode(bytes);
} catch (err) {
console.log(err.name); // "TypeError"
}Use fatal mode when bad input should be rejected, for example when validating uploads. Use lenient mode when showing a best-effort result is acceptable.
How Base64 Represents Bytes as Text
Base64 takes 3 bytes (24 bits) at a time and splits them into four 6-bit values. Each value selects one character from a 64-character alphabet: A–Z, a–z, 0–9, +, and /. When the last group has only 1 or 2 bytes, the output is padded with = to fill out four characters.
btoa and atob, and Why They Reject Unicode
btoa encodes a string to base64, and atob decodes it. Each character in the input is treated as a single byte, so every character must fall between U+0000 and U+00FF. Any character outside that range makes btoa throw.
try {
btoa("€");
} catch (err) {
console.log(err.name); // "InvalidCharacterError"
}
console.log(btoa("hi")); // "aGk="
console.log(atob("aGk=")); // "hi"Unicode-Safe Base64 in the Browser
To make base64 safe for any text, encode the text to UTF-8 first. Then build a "binary string" that holds one character per byte and pass that to btoa. Decoding runs the same steps in reverse. The encoder below converts the bytes in chunks so the spread argument list stays within engine limits on large inputs.
function bytesToBase64(bytes) {
let binary = "";
const chunkSize = 0x8000;
for (let i = 0; i < bytes.length; i += chunkSize) {
binary += String.fromCharCode(...bytes.subarray(i, i + chunkSize));
}
return btoa(binary);
}
function base64ToBytes(base64) {
const binary = atob(base64);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) {
bytes[i] = binary.charCodeAt(i);
}
return bytes;
}
const encoded = bytesToBase64(new TextEncoder().encode("€"));
console.log(encoded); // "4oKs"
console.log(new TextDecoder().decode(base64ToBytes(encoded))); // "€"Exercise
How many base64 characters does a 10-byte input produce, and how many of them are "=" padding?
Show answer
16 characters. 10 bytes make three full 3-byte groups plus 1 leftover byte, which gives 4 groups × 4 characters. The leftover single byte produces two "=" padding characters.