TextEncoder / TextDecoder
TextEncoder converts strings into UTF-8 bytes; TextDecoder converts
UTF-8 bytes back into strings. Use them whenever you move between text
and raw bytes — file contents, request bodies, encoded data.
new TextEncoder()creates an encoder; every encoder produces UTF-8.encoder.encode(string)returns aUint8Arrayof UTF-8 bytes.encoder.encodeInto(source, destination)encodes into an existingUint8Arrayand returns{ read, written }counts.new TextDecoder(label, options)creates a decoder. Thelabelmust identify UTF-8 ("utf-8","utf8", or"unicode-1-1-utf-8"); it defaults to"utf-8". Thefataloption makes decoding throw on malformed input instead of substituting replacement characters.decoder.decode(input)returns the decoded string.decoder.encoding,decoder.fatal, anddecoder.ignoreBOMreflect the constructor options.
Usage#
const encoder = new TextEncoder();
const bytes = encoder.encode("Hello, world!");
console.log(bytes.byteLength); // 13
await fs.writeFile("/out.json", encoder.encode(JSON.stringify({ ok: true })));
Encoding into an existing buffer (useful for fixed-size buffers):
const buffer = new Uint8Array(64);
const { read, written } = new TextEncoder().encodeInto("geartrain", buffer);
console.log(read, written); // 7 7
Decoding bytes back into text:
const decoder = new TextDecoder();
const bytes = await fs.readFile("/data.json");
const data = JSON.parse(decoder.decode(bytes));
Strict decoding:
const strict = new TextDecoder("utf-8", { fatal: true });
try {
strict.decode(maybeCorrupt);
} catch (err) {
console.log("input was not valid UTF-8");
}
Differences from the standard#
- Only UTF-8 is supported. Any other encoding label throws a
RangeErroronnew TextDecoder(label), while the standard defines a large label registry for legacy encodings. decode()does not support thestreamoption and throws if one is passed. Each call must receive complete character sequences; multi-byte characters split across separate decode calls will not reassemble.encode()does not support the deprecatedstreamoption; passing one throws aTypeError.- Passing
fataltodecode()throws aTypeError; the standard ignores unknown options ondecode()(use the constructor instead).