We can use TextDecoder
to decode the bytes to string.
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 set fatal
as true
, then decode
method will throw EncodingError
for invalid characters. By default, it is false
. When fatal
is false
, the invalid characters are replaced by \uFFFD
.decode(buffer, {stream})
The decode
method will decode the stream of bytes to string. This method takes two arguments:
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, set stream
to true
. Set stream
to false
for data that is not chunked and for the last chunk of the data. By default, the stream is set to false
.
// 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:
TextDecoder
object.decode
method.// 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-8
as a label and fatal
set to true
. (If the decoding fails, error will be thrown.)
Called the decode
method with chunk1
and stream
set to true
. This way, the decoder will decode the buffer.
Called the decode
method with chunk2
and stream
set to false
. We set stream
as false
because it is the last buffer, so the decoder will combine the current decode data with previously decoded data and return the decoded string.