Encoding & text
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.)
TextEncoder
ExactEncodes 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".
ReturnsUint8Array — 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')TextDecoder
Works, with caveatsDecodes 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.
Returnsstring — 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))- 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.