本文主要通过两个例子拆解如何使用异步生成器创建一个慢速数据源,并通过 pipeThrough 管道和 TextEncoderStream 、 TextDecoderStream 实现数据的编码解码
# 基础概念:流的三位一体
- 可读流(ReadableStream):数据的源头。数据从这里流出
- 可写流(WritableStream):数据的终点。数据流入这里并被处理
- Transform 流(TransformStream):数据的中间处理器。它接收一种格式的输入流,并输出另一种格式的流(例如:输入字符串 输出字节)
# 示例一:字符串编码与流的创建(源头)
将字符 foo 模拟成每隔一秒到达的数据流,并将其转换为浏览器处理数据所需要的字节格式(UTF-8 编码)
const data = [102, 111, 111]; | |
// A. 异步生成器:数据源 | |
async function* chars() { | |
const encodedText = data.map((x) => Uint8Array.of(x)); | |
for (let charChunk of encodedText) { | |
// 暂停 1 秒,模拟网络延迟 | |
yield await new Promise((resolve) => setTimeout(resolve, 1000, charChunk)); | |
} | |
} | |
// B. 可读流:封装数据源 | |
const encodedTextStream = new ReadableStream({ | |
async start(controller) { | |
// 遍历异步生成器,将数据推入流中 | |
for await (let charChunk of chars()) { | |
controller.enqueue(charChunk); | |
} | |
controller.close(); // 数据发送完毕,关闭流 | |
}, | |
}); | |
// C. 消费者:读取字节数据 | |
const reader = encodedTextStream.getReader(); | |
(async function () { | |
while (true) { | |
const { value, done } = await reader.read(); | |
if (done) break; | |
console.log("字节数据:", value); | |
} | |
})(); |
- 数据源的格式:每个字符都是一个
Uint8Array字节数组,每个字节对应一个字符的 UTF-8 编码,所有涉及网络传输或文件 I/O 的原始数据流,都必须以Uint8Array的形式流动 ReadableStream的启动async start(controller)函数在流被消费时运行for await (let chunk of chars())会暂停,等待chars()生成器每秒yield出一个Uint8Array数据块
# 示例二:管道与实时解码(解码器)
实际应用中,我们需要看到的是字符串,而不是一堆字节数组。这时候就需要使用 TextDecoderStream 将字节流转换为字符串流
将上面的 encodedTextStream 通过 pipeThrough 管道连接到 TextDecoderStream ,即可实现实时解码
//... (chars () 和 encodedTextStream 的定义保持不变) | |
// 新增:解码流 | |
const decodedTextStream = encodedTextStream.pipeThrough( | |
new TextDecoderStream() | |
); | |
// 读取解码流 | |
const reader = decodedTextStream.getReader(); | |
(async function () { | |
while (true) { | |
const { value, done } = await reader.read(); | |
if (done) break; | |
console.log("解码字符:", value); | |
} | |
})(); |
pipeThrough()的力量encodedTextStream.pipeThrough(new TextDecoderStream())创建了一个数据处理管道- 数据流:
Uint8Array流 ->TextDecoderStream->String流 TextDecoderStream接收到上游的字节数组后,立即将其解码为字符串,并将字符串输出到新的流
解码的智能性
- 如果数据是单字节字符(例如 ASCII 字符),
TextDecoderStream会立即将其解码为字符串 - 如果数据是多字节字符(例如 UTF-8 编码的中文字符),
TextDecoderStream会等待足够的字节数,才能将其解码为字符串
[102, 111, 111] -> "foo" [240, 159, 152, 138] -> 😀- 如果数据是单字节字符(例如 ASCII 字符),
# 总结
- 异步生成器:灵活数据源、
ReadableStream:作为数据流的入口- 管道:作为数据处理和格式转换的流水线
TextEncoderStream/TextDecoderStream:作为字节和字符串的转换工具