← 中文资源

简体中文版本

用 StringDecoder 安全拼接跨块拆分的 UTF-8 字节

使用 node:string_decoder 的 StringDecoder.write 缓存跨分片截断的多字节 UTF-8 序列避免乱码,并在末尾通过 end() 显式冲刷残留不完整字节。

阅读英文原文

运行结果

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

naive join   : price: ���12 🚀
decoder join : price: €12 🚀
flushed tail : "" "�" fffd

实现说明

for (const chunk of chunks) 反复执行,循环体之外没有别的重复。唯一的导入来源是 node:buffer、node:string_decoder(Node.js 内建),暴露出 Buffer、StringDecoder。 payload、chunks、naive、decoder 定义在模块顶层,中间不经过函数作用域。

使用要点

  • node:buffer 是 Node.js 内建模块——随运行时自带,无需安装。
  • 每一步打印都带着自己的标签:naive join :、decoder join :、flushed tail :。

常见问题

导入的模块是 npm 包吗?

不需要——node:buffer 内置于 Node.js。node: 前缀就代表核心模块,项目里无需添加任何东西。

核心语句

const naive = chunks.map((c) => c.toString('utf8')).join('');
assembled += decoder.write(chunk);
assembled += decoder.end();

代码示例

import { Buffer } from 'node:buffer';
import { StringDecoder } from 'node:string_decoder';

const payload = Buffer.from('price: €12 🚀', 'utf8');
// Split right in the middle of the 3-byte € sign and 4-byte 🚀 emoji
const chunks = [payload.subarray(0, 8), payload.subarray(8, 13), payload.subarray(13)];

const naive = chunks.map((c) => c.toString('utf8')).join('');
console.log('naive join   :', naive);

const decoder = new StringDecoder('utf8');
let assembled = '';
for (const chunk of chunks) {
  assembled += decoder.write(chunk);
}
assembled += decoder.end();
console.log('decoder join :', assembled);

// A trailing incomplete multi-byte sequence is flushed as U+FFFD on .end()
const partial = new StringDecoder('utf8');
const head = partial.write(Buffer.from([0xe2, 0x82]));
const tail = partial.end();
console.log('flushed tail :', JSON.stringify(head), JSON.stringify(tail), tail.codePointAt(0).toString(16));