What is TextDecoder in JavaScript?
We can use TextDecoder to decode the bytes to string.
Syntax
To create a new TextDencoder call:
let decoder = new TextDecoder(utfLabel, options);
utfLabel: The name of the encoder. Default to “utf-8”. Other valid encoding names can be found here.
option: The option argument has one property.
fatal: If we setfatalastrue, thendecodemethod will throwEncodingErrorfor characters. By default, it isinvalid non-decodable false. Whenfatalisfalse, the invalid characters are replaced by\uFFFD.
Methods in TextDecoder
decode(buffer, {stream})
The decode method will decode the
-
buffer: The bytes to be decoded to string. -
{stream}: An object containing a Boolean property. When data is received in chunks on the network, there is a chance that the multi-byte character, like€, will be split into different chunks. For this case, setstreamtotrue. Setstreamtofalsefor data that is not chunked and for the last chunk of the data. By default, the stream is set tofalse.
Example
// encoded data of "€" is [226, 130, 172]let encodedData = new Uint8Array([226, 130, 172]);let decoder = new TextDecoder();let decodedString = decoder.decode(encodedData);console.log("Decoded String is ", decodedString);
In the code above, we have:
- Created a
TextDecoderobject. - Passed the encoded buffer to the
decodemethod. - Printed the decoded data.
Decoding chunks
// encoded data of "€" is [226, 130, 172]let chunk1 = new Uint8Array([226, 130]);let chunk2 = new Uint8Array([172]);let decoder = new TextDecoder("utf-8", {fatal : true});let decodedString = decoder.decode(chunk1, {stream : true});console.log("After decoding the first chunk", decodedString);decodedString = decoder.decode(chunk2, {stream : false});console.log("Decoded data", decodedString);// test - decoding the. chunk 1 without setting stream to truetry {let decoder2 = new TextDecoder("utf-8", {fatal : true});let decodedString = decoder2.decode(chunk1); // willl throw Error} catch(e) {console.log(e); // The encoded data was not valid.}
In the code above, we have:
-
Created two chunks for the
€character. -
Created a TextDecoder, with
utf-8as a label andfatalset totrue. (If the decoding fails, error will be thrown.) -
Called the
decodemethod withchunk1andstreamset totrue. This way, the decoder will decode the buffer. -
Called the
decodemethod withchunk2andstreamset tofalse. We setstreamasfalsebecause it is the last buffer, so the decoder will combine the current decode data with previously decoded data and return the decoded string.