Skip to content

Commit a177973

Browse files
author
Vladimir Troyanenko
authored
Update article.md
1 parent 61b57df commit a177973

1 file changed

Lines changed: 22 additions & 22 deletions

File tree

Lines changed: 22 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,30 @@
1-
# TextDecoder and TextEncoder
1+
# TextDecoder и TextEncoder
22

3-
What if the binary data is actually a string? For instance, we received a file with textual data.
3+
Что если бинарные данные фактически являются строкой? Например, мы получили файл с текстовыми данными.
44

5-
The build-in [TextDecoder](https://encoding.spec.whatwg.org/#interface-textdecoder) object allows to read the value into an an actual Javascript string, given the buffer and the encoding.
5+
Встроенный [TextDecoder](https://encoding.spec.whatwg.org/#interface-textdecoder) объект позволяет декодировать данные из бинарного буфера в обычную строку.
66

7-
We first need to create it:
7+
Для этого прежде всего нам нужно создать сам декодер:
88
```js
99
let decoder = new TextDecoder([label], [options]);
1010
```
1111

12-
- **`label`** -- the encoding, `utf-8` by default, but `big5`, `windows-1251` and many other are also supported.
13-
- **`options`** -- optional object:
14-
- **`fatal`** -- boolean, if `true` then throw an exception for invalid (non-decodable) characters, otherwise (default) replace them with character `\uFFFD`.
15-
- **`ignoreBOM`** -- boolean, if `true` then ignore BOM (an optional byte-order unicode mark), rarely needed.
12+
- **`label`** -- тип кодировки, `utf-8`используется по умолчанию, но также поддерживаются `big5`, `windows-1251` и многие другие.
13+
- **`options`** -- объект с дополнительными настройками:
14+
- **`fatal`** -- boolean, если `true` тогда генерируется ошибка для не валидных (не декодируемых) символов, в ином случае (по умолчанию) они заменяются символом `\uFFFD`.
15+
- **`ignoreBOM`** -- boolean, если `true` тогда игнорируется BOM (дополнительный признак определяющий порядок следования байтов), что необходимо крайне редко.
1616

17-
...And then decode:
17+
...и после использовать его метод decode:
1818

1919
```js
2020
let str = decoder.decode([input], [options]);
2121
```
2222

23-
- **`input`** -- `BufferSource` to decode.
24-
- **`options`** -- optional object:
25-
- **`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.
23+
- **`input`** -- `BufferSource` бинарный буфер.
24+
- **`options`** -- объект с дополнительными настройками:
25+
- **`stream`** -- true для декодирования потока данных, при этом `decoder` вызывается вновь и вновь для каждого следующего фрагмента данных. В этом случае многобайтовой символ может иногда быть разделен и попасть до разных фрагментов данных. Это опция заставляет `TextDecoder` запомнить "разбитый" символ и декодировать его только после того как придет его недостающая часть.
2626

27-
For instance:
27+
Например:
2828

2929
```js run
3030
let uint8Array = new Uint8Array([72, 101, 108, 108, 111]);
@@ -39,38 +39,38 @@ let uint8Array = new Uint8Array([228, 189, 160, 229, 165, 189]);
3939
alert( new TextDecoder().decode(uint8Array) ); // 你好
4040
```
4141

42-
We can decode a part of the buffer by creating a subarray view for it:
42+
Мы так же может декодировать часть бинарного массива вычленив подмассив :
4343

4444

4545
```js run
4646
let uint8Array = new Uint8Array([0, 72, 101, 108, 108, 111, 0]);
4747

48-
// the string is in the middle
49-
// create a new view over it, without copying anything
48+
// возьмем строку из середины массива
5049
let binaryString = uint8Array.subarray(1, -1);
5150

5251
alert( new TextDecoder().decode(binaryString) ); // Hello
5352
```
5453

5554
## TextEncoder
5655

57-
[TextEncoder](https://encoding.spec.whatwg.org/#interface-textencoder) does the reverse thing -- converts a string into bytes.
56+
[TextEncoder](https://encoding.spec.whatwg.org/#interface-textencoder) поступает наоборот – кодирует строку в бинарный массив.
5857

59-
The syntax is:
58+
Имеет следующий синтаксис:
6059

6160
```js run
6261
let encoder = new TextEncoder();
6362
```
6463

65-
The only encoding it supports is "utf-8".
64+
Поддерживается только "utf-8" кодировка.
6665

67-
It has two methods:
68-
- **`encode(str)`** -- returns `Uint8Array` from a string.
69-
- **`encodeInto(str, destination)`** -- encodes `str` into `destination` that must be `Uint8Array`.
66+
Кодировщик имеет следующие два метода:
67+
- **`encode(str)`** -- возвращает строку закодированную в `Uint8Array` бинарный массив.
68+
- **`encodeInto(str, destination)`** -- кодирует `str` (строку) в `destination` (адресат) который должен быть бинарным массивом `Uint8Array`.
7069

7170
```js run
7271
let encoder = new TextEncoder();
7372

7473
let uint8Array = encoder.encode("Hello");
7574
alert(uint8Array); // 72,101,108,108,111
7675
```
76+

0 commit comments

Comments
 (0)