文本编码

Encoding API 提供了两种将字符串转换为定型数组二进制格式的方法:批量编码和流编码。

把字符串数组转换为定型数组时,编码器始终使用UTF-8。

批量编码

批量编码是通过TextEncoder的实例完成的,这个实例上有encode()方法,该方法接收一个字符串参数,并以Uint8Array格式返回每个字符的UTF-8编码。

const textEncoder = new TextEncoder();

const decodeText = "foo"
const encodeText = textEncoder.encode(decodeText);

编码器实例还有一个encodeInto()方法,该方法接收一个字符串和目标Uint8Array,返回一个字典,该字典包含read和written属性,分别表示成功从源字符串读取了多少字符和向目标数组写入了多少字符。

//encodeInto()
const textEncoder = new TextEncoder();
const fooArr = new Uint8Array(3);
const barArr = new Uint8Array(2);
const fooResult = textEncoder.encodeInto('foo', fooArr);
const barResult = textEncoder.encodeInto('bar',barArr);

流编码

TextEncoderStream,将解码后的文本流通过管道输入流编码器会得到编码后文本块的流。

async function* chars(){
    const decodedText = 'foo';
    for(let char of decodedText){
        yield await new Promise((resolve, reject) =>
            setTimeout(resolve,1000,char)
        );
    }
}

const decodedTextStream = new ReadableStream({
    async start(controller){
        for await (let chunk of chars()){
            controller.enqueue(chunk);
        }
        controller.close();
    }
})

const encodeTextStream = decodedTextStream.pipeThrough(new TextEncoderStream());

const readableStreamDefaultReader = encodeTextStream.getReader();

(async function(){
    while(true){
        const {done,value} = await readableStreamDefaultReader.read();
        if(done){
            break;
        }else{
            console.log(value);
        }
    }
})();