TextEncoder and TextDecoder

UTF-8 encoding, fatal decoding of invalid bytes, and streaming leftover sequences, verified in Node.js 22.23.3.

TextEncoder and TextDecoder convert between JavaScript strings and bytes. TextEncoder supports only UTF-8; encoder.encoding is always "utf-8". These are Encoding standard Web APIs, not String methods and not Node.js Buffer helpers, even though Node 22 exposes the same globals.

Examples were checked in Node.js 22.23.3. They do not read user files. Invalid byte sequences are either replaced or, with fatal: true, throw TypeError.

Examples were checked in Node.js 22.23.3, which provides these Web APIs as built-in globals. This is not a browser DOM test, and the examples do not send network requests. See the MDN documentation for the complete API, including browser support.

Web APIs overview → · JavaScript tutorial and built-in APIs →

API index

APISummary
TextEncoder.encode(), encodeInto(), TextDecoder.decode()Encode a string as UTF-8 bytes, optionally into an existing buffer, and decode those bytes back to a string.
TextDecoder fatal and stream optionsThrow TypeError on invalid UTF-8 when fatal is true, or buffer a partial sequence when stream is true.

UTF-8 encode and decode

encode("café") produces the UTF-8 bytes 99,97,102,195,169, where é is the two-byte sequence C3 A9. A default TextDecoder decodes those bytes back to the same string, and decoder.encoding is "utf-8".

encodeInto writes into an existing Uint8Array and returns { read, written }. The example writes "Hi" into an 8-byte buffer; the remaining bytes stay 0.

TextEncoder.encode(), encodeInto(), TextDecoder.decode()

new TextEncoder()
TextEncoder.prototype.encode(input)
TextEncoder.prototype.encodeInto(source, destination)
new TextDecoder(label, options)
TextDecoder.prototype.decode(input, options)

Encode a string as UTF-8 bytes, optionally into an existing buffer, and decode those bytes back to a string.

ParameterDescription
inputA string for encode, or a binary buffer for decode. The default encoding for TextDecoder is UTF-8.
source, destinationencodeInto reads from source and writes UTF-8 bytes into destination.

Returns: encode returns a Uint8Array. encodeInto returns an object with read and written counts. decode returns a string.

javascript
const encoder = new TextEncoder();
console.log(encoder.encoding);
const bytes = encoder.encode("café");
console.log(Array.from(bytes).join(","));
const decoder = new TextDecoder();
console.log(decoder.decode(bytes));
console.log(decoder.encoding);

const buffer = new Uint8Array(8);
const result = encoder.encodeInto("Hi", buffer);
console.log(result.read, result.written);
console.log(Array.from(buffer).join(","));

Expected output

utf-8
99,97,102,195,169
café
utf-8
2 2
72,105,0,0,0,0,0,0

Related: TypedArray

MDN documentation →

Invalid bytes and streamed sequences

The default decoder replaces invalid UTF-8 with U+FFFD. The bytes FF FE 61 therefore decode as two replacement characters plus "a". The example prints those code points as hex, fffd,fffd,61. With { fatal: true }, the same input throws TypeError.

A split multi-byte character is also an error in fatal mode if you pass only the first byte. Passing { stream: true } holds that leftover and returns an empty string; the next decode call, with the remaining bytes, completes the character 你. This is not a file-reading API, and the example uses only in-memory bytes.

TextDecoder fatal and stream options

new TextDecoder(label, { fatal, ignoreBOM })
TextDecoder.prototype.decode(input, { stream })

Throw TypeError on invalid UTF-8 when fatal is true, or buffer a partial sequence when stream is true.

ParameterDescription
fatalIf true, invalid bytes throw TypeError instead of inserting U+FFFD.
streamIf true, an incomplete sequence is kept for the next decode call instead of being treated as an error or replacement at once.

Returns: A string when the input can be decoded. The example also prints TypeError names for fatal failures.

Throws

  • TypeError — Thrown for invalid or truncated UTF-8 when fatal is true, unless a truncated sequence is deferred with stream: true. Measured in Node.js 22.23.3.
javascript
const invalid = new Uint8Array([0xff, 0xfe, 0x61]);
const replaced = new TextDecoder("utf-8").decode(invalid);
console.log(Array.from(replaced, (ch) => ch.codePointAt(0).toString(16)).join(","));

try {
  new TextDecoder("utf-8", { fatal: true }).decode(invalid);
} catch (error) {
  console.log(error.name);
}

const you = new TextEncoder().encode("你");
console.log(Array.from(you).join(","));
try {
  new TextDecoder("utf-8", { fatal: true }).decode(you.subarray(0, 1));
} catch (error) {
  console.log(error.name);
}

const stream = new TextDecoder("utf-8", { fatal: true });
const first = stream.decode(you.subarray(0, 1), { stream: true });
console.log(JSON.stringify(first));
console.log(stream.decode(you.subarray(1)));

Expected output

fffd,fffd,61
TypeError
228,189,160
TypeError
""
你

MDN documentation →