|
1 | | -# 文本解码器(TextDecoder) 和 文本编码器(TextEncoder) |
| 1 | +# TextDecoder 和 TextEncoder |
2 | 2 |
|
3 | 3 | 如果二进制数据实际上是一个字符串怎么办?例如,我们收到了一个包含文本数据的文件。 |
4 | 4 |
|
5 | | -内置的 [TextDecoder](https://encoding.spec.whatwg.org/#interface-textdecoder) 对象在给定缓冲区(buffer)和编码格式(encoding)的情况下,能够将值读取到实际的 JavaScript 字符串中。 |
| 5 | +内建的 [TextDecoder](https://encoding.spec.whatwg.org/#interface-textdecoder) 对象在给定缓冲区(buffer)和编码格式(encoding)的情况下,能够将值读取到实际的 JavaScript 字符串中。 |
6 | 6 |
|
7 | 7 | 首先我们需要创建: |
8 | 8 | ```js |
9 | 9 | let decoder = new TextDecoder([label], [options]); |
10 | 10 | ``` |
11 | 11 |
|
12 | | -- **`label`** -- 编码格式,默认为 `utf-8`,但同时也支持 `big5`,`windows-1251` 等许多其他编码格式。 |
13 | | -- **`options`** -- 可选对象: |
14 | | - - **`fatal`** -- 布尔值,如果为 `true` 则抛出无效(不可解码)字符异常,否则(默认)替换为字符 `\uFFFD`。 |
15 | | - - **`ignoreBOM`** -- 布尔值,如果为 `true` 则忽略字节顺序标记(BOM)(可选的字节顺序统一码(Unicode)标记),极少情况会需要。 |
| 12 | +- **`label`** —— 编码格式,默认为 `utf-8`,但同时也支持 `big5`,`windows-1251` 等许多其他编码格式。 |
| 13 | +- **`options`** —— 可选对象: |
| 14 | + - **`fatal`** —— 布尔值,如果为 `true` 则为无效(不可解码)字符抛出异常,否则(默认)用字符 `\uFFFD` 替换无效字符。 |
| 15 | + - **`ignoreBOM`** —— 布尔值,如果为 `true` 则 BOM(可选的字节顺序 unicode 标记),很少需要使用。 |
16 | 16 |
|
17 | | -…… 然后开始解码: |
| 17 | +……然后解码: |
18 | 18 |
|
19 | 19 | ```js |
20 | 20 | let str = decoder.decode([input], [options]); |
21 | 21 | ``` |
22 | 22 |
|
23 | | -- **`input`** -- 要被解码的 `BufferSource` 。 |
24 | | -- **`options`** -- 可选对象: |
25 | | - - **`stream`** -- true 为解码流(streams),这时候 decoder 会以传入的数据块(chunks)为参数被重复调用。这种情况下,多字节的字符可能偶尔会在块与块之间被分割。这个选项告诉 `TextDecoder` 去记住 “未完成” 的字符并且在下一个数据块来的时候进行解码。 |
| 23 | +- **`input`** —— 要被解码的 `BufferSource`。 |
| 24 | +- **`options`** —— 可选对象: |
| 25 | + - **`stream`** —— 对于解码流,为 true,则将传入的数据块(chunk)作为参数重复调用 `decoder`。在这种情况下,多字节的字符可能偶尔会在块与块之间被分割。这个选项告诉 `TextDecoder` 记住“未完成”的字符,并在下一个数据块来的时候进行解码。 |
26 | 26 |
|
27 | 27 | 例如: |
28 | 28 |
|
@@ -52,21 +52,21 @@ let binaryString = uint8Array.subarray(1, -1); |
52 | 52 | alert( new TextDecoder().decode(binaryString) ); // Hello |
53 | 53 | ``` |
54 | 54 |
|
55 | | -## 文本编码器 |
| 55 | +## TextEncoder |
56 | 56 |
|
57 | | -[TextEncoder](https://encoding.spec.whatwg.org/#interface-textencoder) 做了相反的事情 -- 将字符串转换为字节。 |
| 57 | +[TextEncoder](https://encoding.spec.whatwg.org/#interface-textencoder) 做相反的事情 —— 将字符串转换为字节。 |
58 | 58 |
|
59 | 59 | 语法为: |
60 | 60 |
|
61 | | -```js run |
| 61 | +```js |
62 | 62 | let encoder = new TextEncoder(); |
63 | 63 | ``` |
64 | 64 |
|
65 | | -支持的编码格式只有 `utf-8` 。 |
| 65 | +只支持 `utf-8` 编码。 |
66 | 66 |
|
67 | 67 | 它有两种方法: |
68 | | -- **`encode(str)`** -- 返回一个字符串被转换得到的 `Uint8Array`。 |
69 | | -- **`encodeInto(str, destination)`** -- 将 `str` 编码到 `destination`中,该目标必须为 `Uint8Array`。 |
| 68 | +- **`encode(str)`** —— 从字符串返回 `Uint8Array`。 |
| 69 | +- **`encodeInto(str, destination)`** —— 将 `str` 编码到 `destination` 中,该目标必须为 `Uint8Array`。 |
70 | 70 |
|
71 | 71 | ```js run |
72 | 72 | let encoder = new TextEncoder(); |
|
0 commit comments