Decode binary payloads
Convert a Uint8Array or other binary view containing encoded text into a JavaScript string.
Node.js · Class
TextDecoder implements the WHATWG Encoding Standard API for converting encoded binary data into JavaScript strings. It supports configurable encodings, streaming chunks, malformed-input handling, and byte-order-mark behavior.
TextDecoder converts encoded binary data into strings. Construct it with an encoding and optional error-handling or byte-order settings, then call decode() for complete data or stream chunks while exposing the selected encoding and decoder behavior through properties.
new TextDecoder([encoding[, options]])
textDecoder.decode(input?, options?): string| Name | Type | Description |
|---|---|---|
encoding | string | Encoding label or alias for the decoder; defaults to UTF-8. |
options | Object | Configuration object. fatal makes decoding failures fatal; ignoreBOM controls byte-order-mark handling. |
input | ArrayBuffer | DataView | TypedArray | Encoded data supplied to decode(). |
options | Object | Configuration for decode(); stream indicates that additional chunks are expected. |
decode() returns a string; encoding is a string property.
const decoder = new TextDecoder();
const bytes = new Uint8Array([72, 101, 108, 108, 111]);
console.log(decoder.decode(bytes)); // HelloCreates a UTF-8 decoder and converts encoded bytes into a JavaScript string.
Convert a Uint8Array or other binary view containing encoded text into a JavaScript string.
Process network or file data arriving across multiple chunks without splitting multibyte characters.
Reject malformed encoded input instead of silently substituting replacement characters.
Preserve or remove a byte-order mark when decoding supported UTF encodings.
TextDecoder implements the WHATWG Encoding Standard API. Its decode method accepts an ArrayBuffer, DataView, or TypedArray and returns a string.
Follow-up: How would you decode data arriving in chunks? Use decode(chunk, { stream: true }) for intermediate chunks, then finish with a decode call that does not continue streaming.
The constructor takes an optional encoding, defaulting to UTF-8, plus options such as fatal and ignoreBOM. The encoding may be a supported encoding or an alias.
Follow-up: What should be checked when choosing a non-UTF encoding? Verify that the requested encoding is supported by the Node.js build and documentation.
The encoding property reports the encoding supported by the instance. The fatal and ignoreBOM settings control malformed-input handling and byte-order-mark treatment.
Follow-up: When is fatal preferable? Use it when silently replacing invalid sequences would hide corrupt or invalid input.
TextEncoderutilArrayBufferDataViewTypedArray