← 中文资源

简体中文版本

TextDecoder 流式解码分块字节

按 4 字节分块解码 UTF-8,stream: true 让跨块的多字节字符挂起等待后续字节,结尾的空参 decode 冲刷残留,文本完整还原。

阅读英文原文

运行结果

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

round trip intact: true
naive café résumé

实现说明

在这里做循环的是 for (let i = 0; i < bytes.length; i += 4)。 演示用的数据放在这几个模块级绑定中:bytes、decoder、text。

使用要点

  • 依赖面只有 node:fs,而它内置于 Node.js。
  • 跑完文件,输出里会留下标记——round trip intact:。

常见问题

它从项目之外导入了什么?

只有 node:fs,而它是 Node.js 内建的——随运行时提供。

核心语句

text += decoder.decode(); // flush: emits whatever was still pending
console.log('round trip intact:', text === 'naive café résumé');
process.on('exit', () => fs.rmSync('notes.txt', { force: true }));
text += decoder.decode(chunk, { stream: true });

代码示例

import fs from 'node:fs';

// Write UTF-8 bytes first, then read them back in fixed-size chunks.
fs.writeFileSync('notes.txt', Buffer.from('naive café résumé', 'utf8'));
const bytes = fs.readFileSync('notes.txt');

const decoder = new TextDecoder('utf-8');
let text = '';

// 4-byte chunks cut inside multi-byte characters on purpose.
for (let i = 0; i < bytes.length; i += 4) {
  const chunk = bytes.subarray(i, i + 4);
  // streaming: true keeps partial sequences pending until more bytes arrive
  text += decoder.decode(chunk, { stream: true });
}
text += decoder.decode(); // flush: emits whatever was still pending

console.log('round trip intact:', text === 'naive café résumé');
console.log(text);

process.on('exit', () => fs.rmSync('notes.txt', { force: true }));