Node.js TextDecoder

Last Updated : 9 Jan, 2023

The TextDecoder is a NodeJS interface that can for a specific text encoding, such as UTF-8, ISO-8859-2, KOI8-R, GBK, etc. decode it.  It takes a stream of bytes as input and gives as output a stream of code points.

Import:

let var = new TextDecoder(encoding);

Parameter:

  •  encoding: It is a string data type that defines the encoding that TextDecoder object will use. By Default UTF-8 is used.

Constructor:

  • TextDecoder( ): This constructor returns a new object which can generate a code point stream with the decoding format specified in the parameter.

Properties:

The TextDecoder does not inherit any property. The defined properties are:

  • TextDecoder.encoding: The name of the encoding format to be used to decode.
  • TextDecoder.fatal: It is a boolean value indicating whether the error code is fatal.
  • TextDecoder.ignoreBOM: It is a boolean value indicating whether BOM(byte order mark) is ignored.

Functions:

  • decode(input): A built-in function decode is used to decode the 'input' using the encoding defined earlier during the construction of the TextDecoder object.

Return Value: A string representing the decoded value for the given encoding format.

Example 1: Let us decode UTF-8 type encoded codepoints. As we know by default 'UTF-8' will be used hence we need not define encoding in the parameters of the decoder constructor. Create a file index.js and write the below code:

JavaScript
let decoder = new TextDecoder();
let uint8Array = new Uint8Array([72, 101, 108, 108, 111]);
console.log(decoder.decode(uint8Array));

Steps to run the application: Write the below command in the terminal to start the server:

node index.js

Output:

Hello

Example 2: To Decode non-UTF-8 encoded values, like A Russian Slogan "Привет, мир!" written in English as "Hello, World". We can use the 'windows-1251' encoding type to decode its code points. Create a file index.js and add the following code: 

JavaScript
let decoder = new TextDecoder('windows-1251');
let data = new Uint8Array([207, 240, 232, 226, 229, 
    242, 44, 32, 236, 232, 240, 33]);
console.log(decoder.decode(data));

Steps to run the application: Write the below command in the terminal to start the server:

node index.js

Output:

Привет, мир!

Browser Compatibility:

BROWSERVERSION SUPPORTED
Chrome38
Edge79
Firefox19
Internet ExplorerNOT SUPPORTED
Opera25
Safari10.1
Android WebView38
Samsung Internet3.0
Deno1.0
NodeJS11.0.0
Safari iOS10.3

Reference: https://nodejs.org/api/util.html#new-textdecoderencoding-options

Comment

Explore