API reference

Encoding & text

2/2Coverage1/2Strict (zero caveats)

Web-standard TextEncoder/TextDecoder for converting between strings and bytes, as Node's own lib/internal/encoding.js. TextEncoder is UTF-8 by definition; TextDecoder decodes UTF-8, UTF-16LE/BE and every single-byte encoding of the WHATWG list (the ISO-8859 and windows code pages, KOI8, IBM866, macintosh), with fatal, ignoreBOM and streaming. The CJK encodings, which Node decodes through ICU, are not supported. (atob/btoa and encodeURI(Component) live under global functions, not here.)

Exact Works, with caveats Not supported

TextEncoder

Exact
new TextEncoder().encode(str: string): Uint8Array; encodeInto(src, dest): { read, written }; encoding: string

Encodes a string to its UTF-8 bytes as a Uint8Array. encodeInto(src, dest) writes whole code points into a caller-supplied Uint8Array and returns { read, written } (read counts UTF-16 code units), and .encoding is "utf-8".

Returns

Uint8Array — The string's UTF-8 bytes.

const encoder = new TextEncoder()
const bytes = encoder.encode("Hello, KlainMainLang!")
console.log(bytes.length)
console.log(bytes[0]) // 72 ('H')
See it in a full example →

TextDecoder

Works, with caveats
new TextDecoder(label?: string).decode(bytes: Uint8Array | ArrayBuffer): string

Decodes any ArrayBuffer, SharedArrayBuffer or ArrayBufferView as UTF-8, UTF-16LE/BE or any single-byte WHATWG encoding (windows-1252 for the latin1/ascii labels, ISO-8859-7/windows-1253 Greek, KOI8-R, …). Invalid or unmapped bytes become U+FFFD, or throw ERR_ENCODING_INVALID_ENCODED_DATA with fatal; a leading byte order mark is dropped unless ignoreBOM; decode(chunk, { stream: true }) keeps an incomplete sequence for the next call.

Returns

string — The decoded UTF-8 text.

const decoder = new TextDecoder()
console.log(decoder.decode(bytes))

const buf = new ArrayBuffer(5)
const view: Uint8Array = new Uint8Array(buf)
view[0] = 72  // H
console.log(decoder.decode(buf))
See it in a full example →
⚠ Differences from standard
  • The CJK encodings (GBK, GB18030, Big5, EUC-JP, EUC-KR, ISO-2022-JP, Shift_JIS), which Node decodes through ICU, throw ERR_ENCODING_NOT_SUPPORTED.