1. 概述
Encoding API 提供了一种机制来处理各种字符编码文本,包括传统的非 UTF-8 编码。
该API提供了四个接口:
TextDecoderTextEncoderTextDecoderStreamTextEncoderStream
2. 接口
2.1 TextDecoder
TextDecoder 接口表示一个文本解码器,一个解码器只支持一种特定文本编码,例如 UTF-8、ISO-8859-2、KOI8-R、GBK,等等。解码器将字节流作为输入,并提供码位流作为输出。
构造函数
TextDecoder()
返回一个新构造的 TextDecoder,它使用参数中指定的解码方法生成码位流。
new TextDecoder()
new TextDecoder(utfLabel)
new TextDecoder(utfLabel, options)
参数:
-
utfLabel可选 。一个字符串,默认是"utf-8"。可以是任意有效的编码。 -
options可选。 一个具有属性的对象:fatal一个布尔值,表示在解码无效数据时,TextDecoder.decode()方法是否必须抛出TypeError。默认是false,这意味着解码器将用替换字符替换错误的数据。
如下例子:
const textDecoder1 = new TextDecoder("iso-8859-2");
const textDecoder2 = new TextDecoder();
const textDecoder3 = new TextDecoder("csiso2022kr", { fatal: true }); // Allows TypeError exception to be thrown.
const textDecoder4 = new TextDecoder("iso-2022-cn"); // Throw a RangeError exception.
属性
TextDecoder 接口不继承任何属性。
-
TextDecoder.prototype.encoding只读一个包含的解码器名称的字符串,即描述
TextDecoder将使用的方法的字符串。 -
TextDecoder.prototype.fatal只读一个布尔值,表示错误模式是否致命。
-
TextDecoder.prototype.ignoreBOM只读一个布尔值,表示是否忽略字节顺序标记(BOM) 标记。如果字节顺序标记被忽略,则是
true;否则是false。
方法
TextDecoder.decode()
TextDecoder.decode() 方法返回一个字符串,其包含作为参数传递的缓冲区解码后的文本。
解码方法在当前的 TextDecoder 对象中定义。这包含了数据的预期编码,以及如何处理解码时发生的错误。
decode()
decode(buffer)
decode(buffer, options)
参数:
-
buffer可选。一个ArrayBuffer、TypedArray或包含要解码的编码文本的DataView对象。 -
options可选。具有以下属性的对象:stream一个布尔标志,表示在后续调用decode()将跟随附加数据。如果以分块的形式处理数据,则设置为true;如果是最终的分块或者数据没有分块,则设置为false。默认是false。
如下实例:编码和解码欧元符号,€。
html
<p>Encoded value: <span id="encoded-value"></span></p>
<p>Decoded value: <span id="decoded-value"></span></p>
javaScript
const encoder = new TextEncoder();
const array = encoder.encode('€'); // Uint8Array(3) [226, 130, 172]
document.getElementById('encoded-value').textContent = array;
const decoder = new TextDecoder();
const str = decoder.decode(array); // String "€"
document.getElementById('decoded-value').textContent = str;
结果:
Encoded value: 226,130,172
Decoded value: €
2.2 TextEncoder
TextEncoder 接受码位流作为输入,并提供 UTF-8 字节流作为输出。
构造函数
TextEncoder()
返回一个新构造的 TextEncoder,它默认使用 UTF-8 编码将码位流转换成字节流。
new TextEncoder();
无参数
属性
TextEncoder 接口不继承任何属性。
TextEncoder.prototype.encoding只读。总是返回utf-8。
TextEncoder.encoding 只读属性返回一个字符串,其中包含特定编码器使用的编码算法的名称。
它只能具有以下值:utf-8。
方法
TextEncoder 接口不继承任何方法。
-
TextEncoder.encode()接受一个字符串作为输入,返回一个包含 UTF-8 编码的文本的
Uint8Array。该方法接受一个字符串作为输入,返回一个对参数中给定的文本的编码后的
Uint8Array,编码的方法通过TextEncoder对象指定。
encode(string)
参数是一个包含了将要编码的文本。
返回值是一个一个 Uint8Array 对象。
如下例子:
html
<p class="source">This is a sample paragraph.</p>
<p class="result">Encoded result: </p>
javaScript
const sourcePara = document.querySelector('.source');
const resultPara = document.querySelector('.result');
const string = sourcePara.textContent;
const textEncoder = new TextEncoder();
let encoded = textEncoder.encode(string);
resultPara.textContent += encoded;
结果:
This is a sample paragraph.
Encoded result: 84,104,105,115,32,105,115,32,97,32,115,97,109,112,108,101,32,112,97,114,97,103,114,97,112,104,46
-
TextEncoder.encodeInto()接受一个字符串(编码的对象)和一个目标
Uint8Array(用于放入生成的 UTF-8 编码的文本)作为输入,并且返回一个指示编码进度的对象。此方法的性能可能会比更早出现的encode()方法好一些。encodeInto(string, uint8Array)参数:
-
string: 一个字符串,包含将要编码的文本。 -
uint8Array:一个Uint8Array对象实例,用于将生成的 UTF-8 编码的文本放入其中。
返回值:
一个对象,包含两个参数。
-
read已经从源字符串中转换为 UTF-8 的,使用 UTF-16 编码的码元数。如果
uint8Array没有足够的空间,则此值可能小于string.length。 -
written在目标
Uint8Array中修改的字节数。写入的的字节确保形成完整的 UTF-8 字节序列。如下实例:
html
<p class="source">This is a sample paragraph.</p> <p class="result"></p>javaScript
const sourcePara = document.querySelector(".source"); const resultPara = document.querySelector(".result"); const string = sourcePara.textContent; const textEncoder = new TextEncoder(); const utf8 = new Uint8Array(string.length); const encodedResults = textEncoder.encodeInto(string, utf8); resultPara.textContent += `Bytes read: ${encodedResults.read}` + ` | Bytes written: ${encodedResults.written}` + ` | Encoded result: ${utf8}`;结果:
This is a sample paragraph.
Bytes read: 27 | Bytes written: 27 | Encoded result: 84,104,105,115,32,105,115,32,97,32,115,97,109,112,108,101,32,112,97,114,97,103,114,97,112,104,46
-
2.3 TextDecoderStream
Encoding API 接口的 TextDecoderStream 方法将二进制编码(如 UTF-8 等)的文本流转换为字符串流。它与 TextDecoder 的流形式等价。
构造函数
TextDecoderStream() 构造函数创建一个新的 TextDecoderStream 对象,该对象用于将二进制编码的文本流转换为字符串。
new TextDecoderStream(label)
new TextDecoderStream(label, options)
参数:
-
label:默认为utf-8的字符串。可以是任意有效的编码。 -
options可选。一个具有属性的TextDecoderOptions对象:fatal一个布尔值,表示错误的模式。如果是 true,则在 decoder 遇到错误时抛出一个DOMException。默认值是false。
如下例子:
从一个 fetch() 中获取并解码二进制数据。如果没有传递任何 label,数据的解码类型为 UTF-8。
const response = await fetch("https://example.com");
const stream = response.body.pipeThrough(new TextDecoderStream());
属性
-
TextDecoderStream.encoding只读。一种编码。 -
TextDecoderStream.fatal只读。一个boolean,表示错误是否是致命的。 -
TextDecoderStream.ignoreBOM只读。一个boolean,表示是否忽略字节顺序标记。 -
TextDecoderStream.readable只读。返回此对象控制的ReadableStream实例。表示可读的字节数据流。 -
TextDecoderStream.writable只读。返回此对象控制的WritableStream实例。将流数据写入目的地(称为接收器)提供了一个标准的抽象。该对象带有内置的背压和队列。
2.4 TextEncoderStream
Encoding API 的 TextEncoderStream 接口将一个字符串流转换为 UTF-8 编码的字节。它与 TextEncoder 的流形式等价。
构造函数
TextEncoderStream() 构造函数创建一个新的 TextEncoderStream 对象,该对象使用 UTF-8 编码将字符串流转换为字节。
new TextEncoderStream()
无参数。
以下例子创建了一个 TextEncoderStream 并且使用它去上传一个文本流。
const body = textStream.pipeThrough(new TextEncoderStream());
fetch('/dest', { method: 'POST', body, headers: {'Content-Type': 'text/plain; charset=UTF-8'} });
属性
-
TextEncoderStream.encoding只读。总是返回"utf-8"。 -
TextEncoderStream.readable只读。返回此对象控制的ReadableStream实例。 -
TextEncoderStream.writable只读。返回此对象控制的WritableStream实例。
总结
以上就是所有Encoding API的相关接口介绍与用法。 参考链接:Encoding API - Web API 接口参考 | MDN (mozilla.org)