Back to Home

TextDecoder and TextEncoder

What if the binary data is actually a string? For instance, we received a file with textual data. The built-in TextDecoder object allows one to read the value into an actual JavaScript string, given the buffer and the encoding. We first need to create it: - label – the encoding, utf-8 by default, but big5, windows-1251 and many other are also supported. - options – optional object: - fatal – boolean, if true then throw an exception for invalid (non-decodable) characters, otherwise (default) replace them with character \uFFFD. - ignoreBOM – boolean, if true then ignore BOM (an optional byte-order Unicode mark), rarely needed. …And then decode: - input – BufferSource to decode. - options – optional object: - stream – true for decoding streams, when decoder is called repeatedly with incoming chunks of data. In that case a multi-byte character may occasionally split between chunks. This options tells TextDecoder to memorize “unfinished” characters and decode them when the next chunk comes. For instance: We can decode a part of the buffer by creating a subarray view for it:

TextEncoder

TextEncoder does the reverse thing – converts a string into bytes. The syntax is: The only encoding it supports is “utf-8”. It has two methods: - encode(str) – returns Uint8Array from a string. - encodeInto(str, destination) – encodes str into destination that must be Uint8Array.

let decoder = new TextDecoder([label], [options]);
Example:

Follow the lesson from Microsoft Web-Dev-For-Beginners course

Tags: web,development