Node.js StringDecoder 实战:让 UTF-8 中文安全跨越 Buffer 分块边界

10-24 5阅读

Node.js StringDecoder 实战:让 UTF-8 中文安全跨越 Buffer 分块边界

配图为独立模型生成的概念示意图,并非软件截图或实际运行界面。字节符号与文字仅用于概念表现,不表示逐项对应的实际解码结果。

读文件、接收网络响应或处理压缩后的字节流时,中文偶尔变成几个问号形状的替换字符,往往不是文件编码突然变了,而是程序把一次读取误当成一个字符边界。系统交给你的块只是一段字节,汉字或表情可能刚好被切在中间。把每块先转成字符串再拼接,会在原始字节仍然完整时提前制造不可逆的信息损失。

本文把实验固定在 Node.js v24.19.0,使用该版本官方文档核对接口。下面九个文件都可独立保存为所示的 .cjs 文件,再执行 node 文件名;无需第三方依赖,不访问网络、不改服务器。每个示例自带断言,后面的输出是同版本实际运行结果。共六十二个具名场景,重点是不同边界的行为,不把重复运行算成额外测试。

阅读时先区分三件事:字节是否完整、编码是否匹配、业务消息是否完整。StringDecoder 只解决其中的增量解码问题。它不会识别一条日志的结束位置,也不会猜测对方究竟发送了哪一种编码。把这三层职责拆开,后面的收尾和校验规则才不会互相打架。

一、先复现:拼接字符串为什么救不回来

“中”的 UTF-8 字节是三个,“😀”是四个。示例故意在字符内部切开,然后对比逐块调用 Buffer.toString 与持续使用同一解码器。ASCII 对照组依然正常,说明“英文没问题”不能证明读取逻辑正确。这里输出中的“�”是 U+FFFD,不是原始数据里的普通问号。

错误路径先丢掉了字节之间的关系,再把已经损坏的字符串拼起来。此时重新编码、再送进 StringDecoder,也无法推断原来的字节。应从最早拿到 Buffer 的位置修正,而不是在页面显示层批量替换字符。若业务本来就有完整且有大小上限的字节消息,先拼完整字节再解码也成立;无限流则不应为此积攒全部内容。

保存为 01_chunk_trap.cjs,运行 node 01_chunk_trap.cjs。

const assert = require('node:assert/strict');
const { StringDecoder } = require('node:string_decoder');
const { Buffer } = require('node:buffer');
function run(name, text, cut, broken) {
  const bytes = Buffer.from(text);
  const chunks = [bytes.subarray(0, cut), bytes.subarray(cut)];
  const wrong = chunks.map(b => b.toString('utf8')).join('');
  const d = new StringDecoder('utf8');
  const right = chunks.map(b => d.write(b)).join('') + d.end();
  assert.equal(wrong, broken);
  assert.equal(right, text);
  console.log(name, JSON.stringify({ wrong, right }));
}
run('trap_bmp_midbyte', '中', 1, '���');
run('trap_astral_midbyte', '😀', 2, '���');
run('trap_ascii_boundary', 'AB', 1, 'AB');
const damaged = Buffer.from([0xe4]).toString('utf8');
const d = new StringDecoder('utf8');
assert.equal(d.end(Buffer.from(damaged)), '�');
console.log('trap_reencoding_is_not_repair', JSON.stringify(damaged));

精确输出:

trap_bmp_midbyte {"wrong":"���","right":"中"}
trap_astral_midbyte {"wrong":"���","right":"😀"}
trap_ascii_boundary {"wrong":"AB","right":"AB"}
trap_reencoding_is_not_repair "�"

二、持续 write:保留跨块状态

给同一份连续字节输入创建一个解码器,按顺序调用 write,并收集每次返回值。它会立即交出可解码的前缀,把末尾暂时缺字节的序列留待后续。返回空字符串是正常状态,不代表源已经结束;只有数据源本身才能告诉你是否还有下一块。

这一组覆盖两字节字符、三字节汉字、四字节表情的内部切点,以及逐字节输入、空块、ASCII 前后缀和控制字符。切点是字节下标,不是 JavaScript 字符串下标。示例用 JSON.stringify 展示结果,所以空字符与换行会显示为转义形式,便于核对终端输出。测试保留原有字节顺序,没有靠重新排序或补字节来“修复”。

保存为 02_utf8_boundaries.cjs,运行 node 02_utf8_boundaries.cjs。

const assert = require('node:assert/strict');
const { StringDecoder } = require('node:string_decoder');
const { Buffer } = require('node:buffer');
const cases = [
  ['split_two_byte', '¢', [1]],
  ['split_three_after_one', '中', [1]],
  ['split_three_after_two', '中', [2]],
  ['split_four_after_one', '😀', [1]],
  ['split_four_after_two', '😀', [2]],
  ['split_four_after_three', '😀', [3]],
  ['split_every_byte', '中😀', [1, 2, 3, 4, 5, 6]],
  ['split_ascii_prefix_suffix', 'A中Z', [2, 3]],
  ['split_empty_between_bytes', '€', [1, 1, 2]],
  ['split_nul_and_newline', '\0中\n', [2, 3]],
];
for (const [name, expected, cuts] of cases) {
  const b = Buffer.from(expected);
  const d = new StringDecoder();
  let from = 0;
  let actual = '';
  for (const to of [...cuts, b.length]) {
    actual += d.write(b.subarray(from, to));
    from = to;
  }
  actual += d.end();
  assert.equal(actual, expected, name);
  console.log(name, JSON.stringify(actual));
}

精确输出:

split_two_byte "¢"
split_three_after_one "中"
split_three_after_two "中"
split_four_after_one "😀"
split_four_after_two "😀"
split_four_after_three "😀"
split_every_byte "中😀"
split_ascii_prefix_suffix "A中Z"
split_empty_between_bytes "€"
split_nul_and_newline "\u0000中\n"

三、end:最后一块与最后一次收尾

读取正常结束后,必须把 end 的返回值也交给下游。它可以直接接收最后一个 Buffer,相当于先处理这块,再收尾;没有最后一块时,调用无参数形式即可。把 end 放在每块后面,会过早宣布输入结束,使跨块字符失去等待下一段的机会。

对于表中那些尚未凑齐的合法 UTF-8 前缀,write 返回空,end 才产生替换字符。已有 ASCII 前缀会先输出,不能因为后面残缺就把前面一起丢掉。这样的替换是容错结果,不证明原文件完整。发生读取错误或连接中断时,应保留异常状态,不要把“能收尾得到字符串”包装成一次成功传输。

保存为 03_end_and_truncation.cjs,运行 node 03_end_and_truncation.cjs。

const assert = require('node:assert/strict');
const { StringDecoder } = require('node:string_decoder');
const { Buffer } = require('node:buffer');
const cases = [
  ['end_empty_stream', [], '', ''],
  ['end_two_byte_lead', [0xc2], '', '�'],
  ['end_three_byte_lead', [0xe4], '', '�'],
  ['end_three_byte_two_bytes', [0xe4, 0xb8], '', '�'],
  ['end_four_byte_lead', [0xf0], '', '�'],
  ['end_four_byte_two_bytes', [0xf0, 0x9f], '', '�'],
  ['end_four_byte_three_bytes', [0xf0, 0x9f, 0x98], '', '�'],
  ['end_prefix_then_truncation', [0x41, 0xe4, 0xb8], 'A', '�'],
];
for (const [name, bytes, before, tail] of cases) {
  const d = new StringDecoder('utf8');
  const got = [d.write(Buffer.from(bytes)), d.end()];
  assert.deepEqual(got, [before, tail], name);
  console.log(name, JSON.stringify(got));
}
const d = new StringDecoder('utf8');
const got = [d.write(Buffer.from([0xe4])), d.end(Buffer.from([0xb8, 0xad]))];
assert.deepEqual(got, ['', '中']);
console.log('end_final_chunk_completes_character', JSON.stringify(got));

精确输出:

end_empty_stream ["",""]
end_two_byte_lead ["","�"]
end_three_byte_lead ["","�"]
end_three_byte_two_bytes ["","�"]
end_four_byte_lead ["","�"]
end_four_byte_two_bytes ["","�"]
end_four_byte_three_bytes ["","�"]
end_prefix_then_truncation ["A","�"]
end_final_chunk_completes_character ["","中"]

四、容错解码不等于通过校验

有些字节不是“还没来齐”,而是已经不可能组成合法的 UTF-8。StringDecoder 没有 fatal 选项;本例中的非法首字节、孤立续字节、过长编码、代理项编码和超出 Unicode 范围的序列都会得到替换输出,而不是因为这些坏字节抛出解码异常。具体替换数量按本例实测,不宜把所有错误概括为“一块只替换一次”。

反过来,结果里出现 U+FFFD 也不能直接判定源数据非法:最后一行的三个字节本来就合法编码了这个字符。因此不要通过搜索结果字符串里的替换符进行严格校验。本例对完整字节输入使用 isUtf8 交叉对照,明确展示“显示一样”与“原始编码有效”是两回事。

保存为 04_invalid_is_not_fatal.cjs,运行 node 04_invalid_is_not_fatal.cjs。

const assert = require('node:assert/strict');
const { StringDecoder } = require('node:string_decoder');
const { Buffer, isUtf8 } = require('node:buffer');
const cases = [
  ['invalid_ff_lead', [0xff], '�', false],
  ['invalid_lone_continuation', [0x80], '�', false],
  ['invalid_overlong_slash', [0xc0, 0xaf], '��', false],
  ['invalid_encoded_surrogate', [0xed, 0xa0, 0x80], '���', false],
  ['invalid_above_unicode_max', [0xf4, 0x90, 0x80, 0x80], '����', false],
  ['invalid_interrupted_sequence', [0xe2, 0x28, 0xa1], '�(�', false],
  ['invalid_test_literal_replacement', [0xef, 0xbf, 0xbd], '�', true],
];
for (const [name, bytes, expected, valid] of cases) {
  const b = Buffer.from(bytes);
  const actual = new StringDecoder('utf8').end(b);
  assert.equal(actual, expected, name);
  assert.equal(isUtf8(b), valid, name);
  console.log(name, JSON.stringify({ actual, valid }));
}

精确输出:

invalid_ff_lead {"actual":"�","valid":false}
invalid_lone_continuation {"actual":"�","valid":false}
invalid_overlong_slash {"actual":"��","valid":false}
invalid_encoded_surrogate {"actual":"���","valid":false}
invalid_above_unicode_max {"actual":"����","valid":false}
invalid_interrupted_sequence {"actual":"�(�","valid":false}
invalid_test_literal_replacement {"actual":"�","valid":true}

五、需要拒绝坏输入时,改用严格流式校验

需要严格拒绝非法 UTF-8 时,可以选择 TextDecoder 的 fatal 模式。持续输入时传 stream: true,完成后再调用一次无参数 decode;省略最后的收尾会漏掉仅在结尾才能确定的截断。示例只断言异常类型,不依赖可能随版本变化的完整报错文案。官方注明 fatal 不支持禁用 ICU 的构建,部署时应确认运行时能力。

即便前几个块已经返回正常文字,后面仍可能失败。如果业务要求整条消息通过验证才提交,应在有长度上限的消息范围内暂存结果,验证结束后再执行有副作用的动作。不能先写入数据库,再假设末尾校验一定通过。另一个常见误区是逐块调用 isUtf8:合法字符的两半各自都可能返回 false,整体才返回 true。

保存为 05_strict_streaming.cjs,运行 node 05_strict_streaming.cjs。

const assert = require('node:assert/strict');
const { TextDecoder } = require('node:util');
const { Buffer, isUtf8 } = require('node:buffer');
function strict(chunks) {
  const d = new TextDecoder('utf-8', { fatal: true });
  let text = '';
  for (const chunk of chunks) text += d.decode(Buffer.from(chunk), { stream: true });
  return text + d.decode();
}
const cases = [
  ['strict_valid_split', [[0xe4], [0xb8, 0xad]], '中'],
  ['strict_valid_empty', [], ''],
  ['strict_bad_leading_byte', [[0xff]], null],
  ['strict_incomplete_at_flush', [[0xe4, 0xb8]], null],
  ['strict_bad_next_chunk', [[0xe4], [0x41]], null],
];
for (const [name, chunks, expected] of cases) {
  if (expected === null) {
    assert.throws(() => strict(chunks), TypeError);
    console.log(name, 'TypeError');
  } else {
    assert.equal(strict(chunks), expected, name);
    console.log(name, JSON.stringify(expected));
  }
}
const parts = [Buffer.from([0xe4]), Buffer.from([0xb8, 0xad])];
const got = [isUtf8(parts[0]), isUtf8(parts[1]), isUtf8(Buffer.concat(parts))];
assert.deepEqual(got, [false, false, true]);
console.log('strict_whole_vs_isolated_chunks', JSON.stringify(got));

精确输出:

strict_valid_split "中"
strict_valid_empty ""
strict_bad_leading_byte TypeError
strict_incomplete_at_flush TypeError
strict_bad_next_chunk TypeError
strict_whole_vs_isolated_chunks [false,false,true]

六、解码器的生命周期跟随哪一条输入

解码器应跟随一条有序的逻辑字节输入,而不是随意做成所有请求共享的全局变量。例中的两份独立消息分别缺了字符尾部和头部,错误地共用状态后竟拼出“中”,看似成功却掩盖了两条消息各自损坏的问题。两个同时进行的来源应各有自己的实例,不能把到达先后当作拼接许可。

官方允许 end 之后复用实例,测试也验证了收尾后的新输入及重复 end。工程上新消息使用新实例通常更易审查;若复用,务必明确调用收尾的边界。空 Buffer 的 write 并不会重置状态。连接断开、消息取消或协议切换时,应按业务规则决定丢弃还是记录未完成数据,不要把剩余状态带入下一位用户的输入。

保存为 06_lifecycle.cjs,运行 node 06_lifecycle.cjs。

const assert = require('node:assert/strict');
const { StringDecoder } = require('node:string_decoder');
const { Buffer } = require('node:buffer');
function check(name, actual, expected) {
  assert.deepEqual(actual, expected, name);
  console.log(name, JSON.stringify(actual));
}
const a = Buffer.from([0xe4, 0xb8]);
const b = Buffer.from([0xad]);
const shared = new StringDecoder();
check('lifecycle_cross_message_contamination',
  [shared.write(a), shared.end(b)], ['', '中']);
check('lifecycle_separate_message_instances',
  [new StringDecoder().end(a), new StringDecoder().end(b)], ['�', '�']);
const reused = new StringDecoder();
check('lifecycle_end_then_reuse',
  [reused.write(a), reused.end(), reused.end(Buffer.from('好'))], ['', '�', '好']);
check('lifecycle_repeated_end_is_empty', [reused.end(), reused.end()], ['', '']);
const kept = new StringDecoder();
check('lifecycle_empty_write_keeps_pending',
  [kept.write(a), kept.write(Buffer.alloc(0)), kept.end(b)], ['', '', '中']);
const first = new StringDecoder();
const second = new StringDecoder();
check('lifecycle_interleaved_independent_sources',
  [first.write(a), second.end(Buffer.from('A')), first.end(b)], ['', 'A', '中']);

精确输出:

lifecycle_cross_message_contamination ["","中"]
lifecycle_separate_message_instances ["�","�"]
lifecycle_end_then_reuse ["","�","好"]
lifecycle_repeated_end_is_empty ["",""]
lifecycle_empty_write_keeps_pending ["","","中"]
lifecycle_interleaved_independent_sources ["","A","中"]

七、编码要在外层约定,不能靠缓存猜测

同一个字节在 latin1 下能表示“é”,在 UTF-8 下却只是一个不完整前缀。缓存更多数据不能纠正选错编码。UTF-16LE 的例子分别切在单个字节和代理对之间,展示同样的跨块问题;这里不把 UTF-8 的非法字节判断直接套用到其他编码。

StringDecoder 不负责自动检测或剥离文件头。本例明确验证 UTF-8 BOM 被保留,并用码点数组显示,避免看不见的字符造成误读。GBK 也不是它支持的编码名。真实协议若允许编码变化,必须先确定消息或字段边界,再为新编码建立独立处理过程;不要在待补齐的旧字符中途切换含义,也不要把已解码的字符串当作原始字节重新处理。

保存为 07_encoding_boundaries.cjs,运行 node 07_encoding_boundaries.cjs。

const assert = require('node:assert/strict');
const { StringDecoder } = require('node:string_decoder');
const { Buffer } = require('node:buffer');
function check(name, actual, expected) {
  assert.deepEqual(actual, expected, name);
  console.log(name, JSON.stringify(actual));
}
const latin = Buffer.from([0xe9]);
check('encoding_latin1_is_explicit', new StringDecoder('latin1').end(latin), 'é');
check('encoding_utf8_cannot_guess_latin1', new StringDecoder('utf8').end(latin), '�');
const le = new StringDecoder('utf16le');
const word = Buffer.from('中', 'utf16le');
check('encoding_utf16le_odd_byte_split',
  [le.write(word.subarray(0, 1)), le.end(word.subarray(1))], ['', '中']);
const pair = new StringDecoder('utf16le');
const face = Buffer.from('😀', 'utf16le');
check('encoding_utf16le_surrogate_split',
  [pair.write(face.subarray(0, 2)), pair.end(face.subarray(2))], ['', '😀']);
const bom = new StringDecoder('utf8').end(Buffer.from([0xef, 0xbb, 0xbf, 0x41]));
check('encoding_bom_is_preserved', [...bom].map(c => c.codePointAt(0)), [65279, 65]);
assert.throws(() => new StringDecoder('gbk'), { code: 'ERR_UNKNOWN_ENCODING' });
console.log('encoding_unsupported_gbk', 'ERR_UNKNOWN_ENCODING');

精确输出:

encoding_latin1_is_explicit "é"
encoding_utf8_cannot_guess_latin1 "�"
encoding_utf16le_odd_byte_split ["","中"]
encoding_utf16le_surrogate_split ["","😀"]
encoding_bom_is_preserved [65279,65]
encoding_unsupported_gbk ERR_UNKNOWN_ENCODING

八、只想读取文本流,可以直接 setEncoding

如果对象已经是 Node 的 Readable,且后续只需要文本,setEncoding 是更简短的入口。官方说明它会处理跨块多字节字符;此后消费端拿到字符串,不应再对每块调用 Buffer 解码。这个例子用内存字节构建普通字节流,异步遍历得到最终文本。

测试只约束内容及返回类型,不假设每次输入会对应一次输出。流可能合并或改变可见块的划分,业务代码不能把事件次数当作消息数量。setEncoding 同样不是严格的 UTF-8 验证器,截断和非法字节仍需要按业务要求处理。若还要保存或校验原始字节,应在明确的一层完成解码,避免不同消费者对同一份数据含义产生分歧。

保存为 08_readable_setencoding.cjs,运行 node 08_readable_setencoding.cjs。

const assert = require('node:assert/strict');
const { Readable } = require('node:stream');
const { Buffer } = require('node:buffer');
async function collect(parts) {
  const stream = Readable.from(parts.map(p => Buffer.from(p)), { objectMode: false });
  stream.setEncoding('utf8');
  let result = '';
  for await (const text of stream) {
    assert.equal(typeof text, 'string');
    result += text;
  }
  return result;
}
(async () => {
  const cases = [
    ['readable_bmp_split', [[0xe4], [0xb8, 0xad]], '中'],
    ['readable_astral_bytewise', [[0xf0], [0x9f], [0x98], [0x80]], '😀'],
    ['readable_empty_source', [], ''],
    ['readable_truncated_eof', [[0xe4, 0xb8]], '�'],
    ['readable_invalid_byte', [[0xff]], '�'],
    ['readable_complete_plus_tail', [[0x41], [0xe4]], 'A�'],
  ];
  for (const [name, chunks, expected] of cases) {
    const actual = await collect(chunks);
    assert.equal(actual, expected, name);
    console.log(name, JSON.stringify(actual));
  }
})().catch(error => { console.error(error); process.exitCode = 1; });

精确输出:

readable_bmp_split "中"
readable_astral_bytewise "😀"
readable_empty_source ""
readable_truncated_eof "�"
readable_invalid_byte "�"
readable_complete_plus_tail "A�"

九、字符完整之后,还要处理业务分帧

最后把增量解码与按行读取分开:解码器维护字节尾部,pending 维护尚未遇到换行的文本。一个块可能包含多行,也可能只有半个汉字;CR 与 LF 甚至可能分属两块。先将完整文本接到缓冲区,再循环寻找换行,职责会清楚得多。

本例明确约定:遇到换行就产生一条记录,移除紧邻换行的一个回车;末尾没有换行的非空文本仍保留,末尾换行不额外制造空记录,而真正的空行保留。结束时先接收 decoder.end,再处理最后一行,所以截断替换不会悄悄漏掉。它是小数据教学实现,生产中还需限制最长行与总量,并处理下游背压;不能让无换行输入无限占用内存。

保存为 09_decode_then_frame.cjs,运行 node 09_decode_then_frame.cjs。

const assert = require('node:assert/strict');
const { StringDecoder } = require('node:string_decoder');
const { Buffer } = require('node:buffer');
function lines(chunks) {
  const d = new StringDecoder('utf8');
  const out = [];
  let pending = '';
  function accept(text) {
    pending += text;
    let i;
    while ((i = pending.indexOf('\n')) >= 0) {
      out.push(pending.slice(0, i).replace(/\r$/, ''));
      pending = pending.slice(i + 1);
    }
  }
  for (const chunk of chunks) accept(d.write(chunk));
  accept(d.end());
  if (pending !== '') out.push(pending); // Keep an unterminated final line.
  return out;
}
const cases = [
  ['frame_utf8_inside_line', '中\n', [1, 2], ['中']],
  ['frame_crlf_across_chunks', 'A\r\nB\n', [2], ['A', 'B']],
  ['frame_two_lines_one_chunk', 'A\nB\n', [], ['A', 'B']],
  ['frame_unterminated_last_line', '中', [1], ['中']],
  ['frame_final_newline_no_extra_line', 'A\n', [1], ['A']],
  ['frame_blank_line_is_record', '\n', [], ['']],
  ['frame_empty_input_has_no_record', '', [], []],
];
for (const [name, text, cuts, expected] of cases) {
  const b = Buffer.from(text);
  const chunks = [];
  let from = 0;
  for (const to of [...cuts, b.length]) {
    chunks.push(b.subarray(from, to));
    from = to;
  }
  const actual = lines(chunks);
  assert.deepEqual(actual, expected, name);
  console.log(name, JSON.stringify(actual));
}
const actual = lines([Buffer.from([0xe4, 0xb8])]);
assert.deepEqual(actual, ['�']);
console.log('frame_flushes_incomplete_final_line', JSON.stringify(actual));

精确输出:

frame_utf8_inside_line ["中"]
frame_crlf_across_chunks ["A","B"]
frame_two_lines_one_chunk ["A","B"]
frame_unterminated_last_line ["中"]
frame_final_newline_no_extra_line ["A"]
frame_blank_line_is_record [""]
frame_empty_input_has_no_record []
frame_flushes_incomplete_final_line ["�"]

收尾检查

排查时依次检查:原始字节有没有在字符中间分块,是否持续复用正确实例,是否收集每次 write 与最终 end 的结果,独立消息是否隔离,以及业务究竟要容错展示还是拒绝坏输入。不要仅靠一份没有中文的样本判断实现正确。

还要记住,字符完整不代表视觉上的一个字已经完整:组合音标、肤色修饰符和零宽连接符参与的表情,可以由多个 Unicode 码点构成。解码器不会为界面动画或编辑器自动聚合这些显示单元。这里讨论的是编码字节边界,不是语言学意义的字符分段;需要按用户可见字符操作时,应另外采用适合的分段规则。

边界测试的价值在于验证约定,而不是证明所有输入都安全。本文六十二个具名场景覆盖展示的常见分块、非法输入、收尾、生命周期、编码及分帧规则;它们不是完整协议测试,更不等于对外部数据的安全保证。

一手资料与验证范围

资料核对与代码验证日期:2026 年 10 月 24 日。运行版本固定为 v24.19.0,不将文档入口的后续版本变化冒充为本次测试结果。

文章版权声明:除非注明,否则均为云鹊BLOG原创文章,转载或复制请以超链接形式并注明出处。