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 a Uint8Array of UTF-8 bytes.
  • encoder.encodeInto(source, destination) encodes into an existing Uint8Array and returns { read, written } counts.
  • new TextDecoder(label, options) creates a decoder. The label must identify UTF-8 ("utf-8", "utf8", or "unicode-1-1-utf-8"); it defaults to "utf-8". The fatal option makes decoding throw on malformed input instead of substituting replacement characters.
  • decoder.decode(input) returns the decoded string.
  • decoder.encoding, decoder.fatal, and decoder.ignoreBOM reflect 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 RangeError on new TextDecoder(label), while the standard defines a large label registry for legacy encodings.
  • decode() does not support the stream option 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 deprecated stream option; passing one throws a TypeError.
  • Passing fatal to decode() throws a TypeError; the standard ignores unknown options on decode() (use the constructor instead).

Documentation#