← 中文资源

简体中文版本

TextDecoder 流式解码跨块多字节字符

载荷在多字节字符中间被切开时,必须用 stream: true 保留未完字节等下一块;一次性解码只会把残缺前缀变成替换符,fatal 模式则直接抛 TypeError。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

chars: 6 bytes: 10
streamed ok: true
broken prefix: "caf�"
fatal: TypeError

实现说明

演示用的数据放在这几个模块级绑定中:text、bytes、mid、rest。

使用要点

  • 每一步打印都带着自己的标签:chars:、streamed ok:、broken prefix:。

常见问题

这段代码会引入外部包吗?

不涉及外部包,每个调用都落在内建 API 上。 状态都挂在模块顶层:text、bytes、mid。

核心语句

const text = "café \u{1F680}";          // é is 2 bytes, the rocket is 4 in UTF-8
const bytes = new TextEncoder().encode(text);
const streamed = decoder.decode(mid, { stream: true }) + decoder.decode(rest);
new TextDecoder("utf-8", { fatal: true }).decode(mid);

代码示例

// Pick a split point that lands inside a multibyte sequence.
const text = "café \u{1F680}";          // é is 2 bytes, the rocket is 4 in UTF-8
const bytes = new TextEncoder().encode(text);
console.log("chars:", [...text].length, "bytes:", bytes.length);

// byte 4 falls inside é (bytes 3-4): the boundary is mid-codepoint
const mid = bytes.slice(0, 4);
const rest = bytes.slice(4);

const decoder = new TextDecoder();
const streamed = decoder.decode(mid, { stream: true }) + decoder.decode(rest);
console.log("streamed ok:", streamed === text);

// one-shot decode of the broken prefix: trailing replacement character
console.log("broken prefix:", JSON.stringify(new TextDecoder().decode(mid)));

// fatal mode turns the same broken bytes into a TypeError
try {
  new TextDecoder("utf-8", { fatal: true }).decode(mid);
} catch (error) {
  console.log("fatal:", (error as TypeError).name);
}