diff --git a/4-binary/02-text-decoder/article.md b/4-binary/02-text-decoder/article.md index a0c80145c..f7aacb829 100644 --- a/4-binary/02-text-decoder/article.md +++ b/4-binary/02-text-decoder/article.md @@ -1,30 +1,30 @@ -# TextDecoder and TextEncoder +# TextDecoder та TextEncoder -What if the binary data is actually a string? For instance, we received a file with textual data. +А якщо бінарні дані є просто рядком? Наприклад, ми отримали файл з текстовими даними. -The built-in [TextDecoder](https://encoding.spec.whatwg.org/#interface-textdecoder) object allows one to read the value into an actual JavaScript string, given the buffer and the encoding. +Вбудований об’єкт [TextDecoder](https://encoding.spec.whatwg.org/#interface-textdecoder) дає змогу записати дані в JavaScript рядок із заданого буферу з потрібним кодуванням. -We first need to create it: +Але для початку його необхідно створити: ```js let decoder = new TextDecoder([label], [options]); ``` -- **`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. +- **`label`** -- кодування, типово `utf-8`, але також підтримуються `big5`, `windows-1251` та багато інших кодувань. +- **`options`** -- необов’язковий об’єкт, який задає додаткові налаштування декодера: + - **`fatal`** -- булевий параметр, якщо передано `true` -- буде згенеровано виключення для символів, які не вдасться декодувати, в іншому випадку (типово) вони будуть замінені на символ `\uFFFD`. + - **`ignoreBOM`** -- булевий параметр, якщо передано `true` -- буде проігноровано BOM (Byte order mark — необов’язковий маркер порядку байтів), рідко трапляється в нагоді. -...And then decode: +...А потім декодувати: ```js let str = decoder.decode([input], [options]); ``` -- **`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. +- **`input`** -- `BufferSource` буфер для декодування. +- **`options`** -- необов’язковий об’єкт: + - **`stream`** -- значення `true`, якщо потрібно декодувати потік (stream), тоді `decoder` буде викликано повторно декілька разів для отримання вхідних даних частинами. В такому випадку символи, що складають з декількох байт можуть бути випадково розділеними між частинами. Ця опція дозволяє `TextDecoder` запам’ятати "незакінчені" символи для декодування разом з наступною частиною. -For instance: +Наприклад: ```js run let uint8Array = new Uint8Array([72, 101, 108, 108, 111]); @@ -39,14 +39,14 @@ let uint8Array = new Uint8Array([228, 189, 160, 229, 165, 189]); alert( new TextDecoder().decode(uint8Array) ); // 你好 ``` -We can decode a part of the buffer by creating a subarray view for it: +Також можливо частково декодувати буфер за допомогою створення представлення тільки з частиною масиву: ```js run let uint8Array = new Uint8Array([0, 72, 101, 108, 108, 111, 0]); -// the string is in the middle -// create a new view over it, without copying anything +// рядок всередині між першим та останнім байтом +// створення нового представлення без копіювання масиву let binaryString = uint8Array.subarray(1, -1); alert( new TextDecoder().decode(binaryString) ); // Hello @@ -54,19 +54,19 @@ alert( new TextDecoder().decode(binaryString) ); // Hello ## TextEncoder -[TextEncoder](https://encoding.spec.whatwg.org/#interface-textencoder) does the reverse thing -- converts a string into bytes. +[TextEncoder](https://encoding.spec.whatwg.org/#interface-textencoder) працює зворотнім чином -- перетворює рядок в байти. -The syntax is: +Синтаксис: ```js let encoder = new TextEncoder(); ``` -The only encoding it supports is "utf-8". +Підтримується тільки кодування "utf-8". -It has two methods: -- **`encode(str)`** -- returns `Uint8Array` from a string. -- **`encodeInto(str, destination)`** -- encodes `str` into `destination` that must be `Uint8Array`. +Об’єкт має два методи: +- **`encode(str)`** -- повертає `Uint8Array` створений з рядку. +- **`encodeInto(str, destination)`** -- `str` буде закодовано та записано в `destination`. Параметр `destination` повинен мати тип `Uint8Array`. ```js run let encoder = new TextEncoder();