JavaScript UTF-8 边界实战:TextDecoder 的 fatal、BOM 与流式解码
处理上传文件、二进制协议或分块响应时,乱码常常出现在边界处:把字符串长度当成字节数,把一次读取当成一个完整字符,或者看见 decode 返回字符串就认定输入没有问题。本文用五个独立实验把这些判断拆开,每一组都保留会失败的错误假设检查,让问题能在改代码时直接暴露。
测试环境为实际本地 Node.js v24.19.0,核验日期为北京时间 2026 年 10 月 24 日。所有程序只使用内置 API 与 node:assert/strict,不安装 npm 包,不访问网络,也不依赖计时结果。它们验证的是明确给出的输入与运行时行为,不代表完成了所有浏览器或 Node.js 构建配置的兼容性测试。

一、先分清码元、码点和 UTF-8 字节
JavaScript 字符串的 length 统计 UTF-16 码元,不能直接用来填写 UTF-8 字节长度。这一定义来自 ECMAScript String 类型规范。下面特意把 ASCII、汉字和补充平面字符放在同一个字符串中,避免只用英文测试时掩盖计量单位的差别。
对于本例 A中🙂,四个码元、三个码点和八个字节会同时出现。这里的码点数量也不应直接称为用户眼中的字符数量;本例没有组合附加符号和复杂 emoji 序列,不能据此推广为界面字符计数算法。真正需要写入二进制长度字段时,直接使用编码结果的 byteLength 更清楚。
encodeInto 适合写入已有 Uint8Array:read 对应消耗的源字符串码元,written 对应写出的字节,两个字段不能互换。这个接口定义见 Node.js encodeInto 文档。实验故意只给五个字节,验证剩下一个位置不会被写成半个 emoji。
保存为 01_units.mjs,运行 node 01_units.mjs。成功时标准输出如下方所列;任何断言失败都会使程序退出。
import assert from 'node:assert/strict';
const encoder = new TextEncoder();
const decoder = new TextDecoder('utf-8', { fatal: true });
const text = 'A中🙂';
const bytes = encoder.encode(text);
const hex = value => Array.from(value, b => b.toString(16).padStart(2, '0')).join(' ');
assert.equal(encoder.encoding, 'utf-8');
assert.equal(text.length, 4);
assert.equal([...text].length, 3);
assert.equal(bytes.byteLength, 8);
assert.equal(hex(bytes), '41 e4 b8 ad f0 9f 99 82');
assert.equal(decoder.decode(bytes), text);
// Wrong assumption: UTF-16 code units equal UTF-8 bytes.
assert.notEqual(text.length, bytes.byteLength);
const dest = new Uint8Array(5);
const progress = encoder.encodeInto(text, dest);
assert.deepEqual(progress, { read: 2, written: 4 });
assert.equal(decoder.decode(dest.subarray(0, progress.written)), 'A中');
assert.equal(dest[4], 0);
const remainder = encoder.encode(text.slice(progress.read));
assert.equal(decoder.decode(remainder), '🙂');
// Wrong offset: written counts bytes, not source string code units.
assert.equal(text.slice(progress.written), '');
assert.notEqual(text.slice(progress.written), '🙂');
for (const lone of ['\uD800', '\uDC00']) {
assert.equal(hex(encoder.encode(lone)), 'ef bf bd');
assert.equal(decoder.decode(encoder.encode(lone)), '\uFFFD');
assert.notEqual(decoder.decode(encoder.encode(lone)), lone);
}
console.log(`units=${text.length} codePoints=${[...text].length} utf8Bytes=${bytes.byteLength}`);
console.log(`bytes=${hex(bytes)}`);
console.log(`encodeInto=${JSON.stringify(progress)}`);
console.log(`remainder=${decoder.decode(remainder)}`);
console.log('loneHigh=ef bf bd loneLow=ef bf bd');
console.log('wrongAssumptionsRejected=true');
预期标准输出:
units=4 codePoints=3 utf8Bytes=8
bytes=41 e4 b8 ad f0 9f 99 82
encodeInto={"read":2,"written":4}
remainder=🙂
loneHigh=ef bf bd loneLow=ef bf bd
wrongAssumptionsRejected=true
运行结果里 read 为二,written 为四,所以继续编码应从 text.slice(read) 开始。若使用 written 去切源字符串,本例会把最后的 emoji 整个跳过。目标缓冲区的第五个字节仍然为零,它只是未写入的空间;实际发送时也只能取 written 指定的窗口,不能把整块预分配空间当作有效内容。
同一程序还分别编码了孤立的高代理项和低代理项。两者都变成 EF BF BD,解码后得到 U+FFFD,而非原始孤立码元。TextEncoder 的输入采用 USVString 转换,相关定义见 Encoding Standard 的 TextEncoder 接口与 Web IDL 的 USVString 转换。因此,能够成功编码不足以证明原 JavaScript 字符串没有孤立代理项;若业务需要拒绝这种输入,应在编码之前另行检查,别指望事后无损还原。
二、fatal 检查编码错误,不替代数据格式检查
第二个实验使用 E4 B8 41:前两个字节像是三字节序列的开头,后面却来了 ASCII 字母 A。默认模式的输出是替换字符加 A;严格模式则抛出 TypeError。fatal 与 decode 的异常行为可对照 Node.js TextDecoder.decode 文档。该文档同时注明:禁用 ICU 的 Node.js 构建不支持 fatal 选项,不能把本文结果泛化到这类构建。例子只断言异常类型,不依赖可能随版本变化的英文错误文案。
保存为 02_fatal.mjs,运行 node 02_fatal.mjs。成功时标准输出如下方所列;任何断言失败都会使程序退出。
import assert from 'node:assert/strict';
const encoder = new TextEncoder();
const malformed = Uint8Array.of(0xe4, 0xb8, 0x41);
const replacement = new TextDecoder('utf-8').decode(malformed);
assert.equal(replacement, '\uFFFDA');
assert.equal(replacement.codePointAt(1), 0x41);
assert.throws(
() => new TextDecoder('utf-8', { fatal: true }).decode(malformed),
TypeError,
);
// Wrong assumption: decoding then re-encoding preserves malformed bytes.
assert.notDeepEqual(encoder.encode(replacement), malformed);
// U+FFFD can be valid original content, not evidence of a decoder error.
const literalReplacement = encoder.encode('\uFFFD');
assert.equal(
new TextDecoder('utf-8', { fatal: true }).decode(literalReplacement),
'\uFFFD',
);
const notJSON = '{"x":1,}';
const validText = new TextDecoder('utf-8', { fatal: true }).decode(encoder.encode(notJSON));
assert.equal(validText, notJSON);
assert.throws(() => JSON.parse(validText), SyntaxError);
console.log(`replacement=${JSON.stringify(replacement)}`);
console.log('fatal=TypeError');
console.log('roundTripPreservesMalformed=false');
console.log('literalReplacementIsValidUtf8=true');
console.log('validUtf8IsValidJson=false');
预期标准输出:
replacement="�A" fatal=TypeError roundTripPreservesMalformed=false literalReplacementIsValidUtf8=true validUtf8IsValidJson=false
这组结果给出了两个实际排查方向。第一,默认替换之后再编码已经改变了原始字节,不能把这个过程当作二进制归档或精确转发方法。若还需要追查数据来源,应保留原始字节及对应位置,而不是只保留显示出来的字符串。
第二,文本里出现 U+FFFD 不足以证明刚刚发生解码错误,因为发送者完全可以把该字符作为合法内容编码。本例把字面量 U+FFFD 编码后交给 fatal 模式,照样通过。反过来,带末尾逗号的 JSON 示例也是合法 UTF-8 文本,只有进入 JSON.parse 才被拒绝。编码层、格式解析层、字段约束与业务权限检查应分开设计;不能把 fatal 描述成通用安全过滤器。
三、ignoreBOM 为 true,结果反而保留开头标记
这个选项最容易凭名字猜错。对 UTF-8 而言,默认 ignoreBOM 为 false,会识别并省略解码输入开头的 BOM;设为 true,则不进行这一步特殊省略,结果保留 U+FEFF。这里“忽略”的是 BOM 的特殊处理意义,不是把相关字符从输出里全部删掉。具体规则可核对 Encoding Standard 的输出序列化算法。
为了避免不可见字符被终端或复制过程掩盖,下面把每个码点打印成十六进制。输入中放了两段 EF BB BF:一段在开头,一段在 A 与 B 之间。这样一次运行就能区分开头标记处理和全文删除,两种操作在本例中会得到不同结果。
保存为 03_bom.mjs,运行 node 03_bom.mjs。成功时标准输出如下方所列;任何断言失败都会使程序退出。
import assert from 'node:assert/strict';
const bytes = Uint8Array.of(0xef, 0xbb, 0xbf, 0x41, 0xef, 0xbb, 0xbf, 0x42);
const normal = new TextDecoder('utf-8');
const preserve = new TextDecoder('utf-8', { ignoreBOM: true });
const a = normal.decode(bytes);
const b = preserve.decode(bytes);
assert.equal(normal.ignoreBOM, false);
assert.equal(preserve.ignoreBOM, true);
assert.equal(a, 'A\uFEFFB');
assert.equal(b, '\uFEFFA\uFEFFB');
// Wrong assumption: ignoreBOM=true removes BOM from the result.
assert.notEqual(b, 'AB');
assert.notEqual(b, a);
// Wrong assumption: default decoding deletes every U+FEFF.
assert.notEqual(a, 'AB');
const stream = new TextDecoder('utf-8', { fatal: true });
const first = stream.decode(Uint8Array.of(0xef), { stream: true });
const second = stream.decode(Uint8Array.of(0xbb, 0xbf, 0x41), { stream: true });
const final = stream.decode();
assert.deepEqual([first, second, final], ['', 'A', '']);
const points = s => [...s].map(c => c.codePointAt(0).toString(16).padStart(4, '0')).join(' ');
console.log(`default=${points(a)}`);
console.log(`ignoreBOM=true=${points(b)}`);
console.log(`splitBOM=${JSON.stringify([first, second, final])}`);
console.log('interiorUFEFFPreserved=true');
预期标准输出:
default=0041 feff 0042 ignoreBOM=true=feff 0041 feff 0042 splitBOM=["","A",""] interiorUFEFFPreserved=true
默认输出仍含中间的 FEFF;preserve 实例则保留开头和中间的两个 FEFF。因此,不要把 ignoreBOM 当成清洗文件中全部不可见字符的开关。若业务确实禁止某些字符,应写出具体规则,并区分文件标记和正文内容,避免悄悄改变数据。
后半部分把开头 BOM 拆成 EF 与 BB BF 两块。使用同一个流式解码器,第一块返回空串,第二块返回 A,最后清空状态仍返回空串。这与前三个字节一次到齐的结果一致。空串在这里表示暂时没有完整输出,不能直接当成读取结束。
四、分块可以落在字符内部,结束时必须 flush
第四个实验把 A中🙂Z 的九个字节切成四块,故意同时跨越汉字和 emoji 的内部边界。正确路径维持同一个 TextDecoder,每块使用 stream: true,输入结束后调用一次无参数 decode。这个结束调用在下文称为 flush,处理步骤见 Encoding Standard 的 decode 算法。
错误路径则为每一块创建新解码器,把每块当作独立完整输入。两条路径读取的是同一批字节;因此输出差异来自状态管理,而非网络、文件内容或字体。程序还遍历全部十个二分切点,包括空首块和空尾块,用断言验证拼接结果不随这些切点改变。
保存为 04_stream.mjs,运行 node 04_stream.mjs。成功时标准输出如下方所列;任何断言失败都会使程序退出。
import assert from 'node:assert/strict';
const text = 'A中🙂Z';
const bytes = new TextEncoder().encode(text);
assert.equal(bytes.byteLength, 9);
const chunks = [bytes.subarray(0, 2), bytes.subarray(2, 5), bytes.subarray(5, 7), bytes.subarray(7)];
const decoder = new TextDecoder('utf-8', { fatal: true });
const parts = chunks.map(chunk => decoder.decode(chunk, { stream: true }));
const tail = decoder.decode();
assert.deepEqual(parts, ['A', '中', '', '🙂Z']);
assert.equal(tail, '');
assert.equal(parts.join('') + tail, text);
// Wrong variant: each chunk is treated as a complete, separate input.
const wrong = chunks.map(chunk => new TextDecoder().decode(chunk)).join('');
assert.equal(wrong, 'A' + '\uFFFD'.repeat(7) + 'Z');
assert.notEqual(wrong, text);
let cutsChecked = 0;
for (let cut = 0; cut <= bytes.byteLength; cut++) {
const d = new TextDecoder('utf-8', { fatal: true });
const result = d.decode(bytes.subarray(0, cut), { stream: true })
+ d.decode(bytes.subarray(cut), { stream: true }) + d.decode();
assert.equal(result, text);
cutsChecked++;
}
const incomplete = Uint8Array.of(0xe4, 0xb8);
const tolerant = new TextDecoder();
const pending = tolerant.decode(incomplete, { stream: true });
const flushed = tolerant.decode();
assert.equal(pending, '');
assert.equal(flushed, '\uFFFD');
assert.notEqual(pending, pending + flushed); // Omitting flush loses evidence.
const strict = new TextDecoder('utf-8', { fatal: true });
assert.equal(strict.decode(incomplete, { stream: true }), '');
assert.throws(() => strict.decode(), TypeError);
// stream=true delays incomplete suffixes, not already invalid sequences.
assert.throws(() => new TextDecoder('utf-8', { fatal: true }).decode(
Uint8Array.of(0xe4, 0x41), { stream: true },
), TypeError);
console.log(`parts=${JSON.stringify(parts)}`);
console.log(`result=${parts.join('') + tail}`);
console.log(`wrong=${JSON.stringify(wrong)}`);
console.log(`allTwoChunkCuts=${cutsChecked}`);
console.log(`incomplete=${JSON.stringify([pending, flushed])}`);
console.log('strictFinalFlush=TypeError');
console.log('strictInvalidChunk=TypeError');
预期标准输出:
parts=["A","中","","🙂Z"] result=A中🙂Z wrong="A�������Z" allTwoChunkCuts=10 incomplete=["","�"] strictFinalFlush=TypeError strictInvalidChunk=TypeError
正确路径返回 A、中、空串、🙂Z 四段;错误路径得到七个替换字符。这说明分块后分别 decode 再拼字符串,会在多字节字符被切断时造成信息损失。即使某次英文测试通过,也不能证明这种写法适合任意 UTF-8 内容。
更隐蔽的问题在结尾。只输入 E4 B8 并保持 stream: true 时,宽松与严格解码器都暂时返回空串,因为它们还在等待第三个字节。真正声明结束后,宽松模式输出 U+FFFD,严格模式抛出 TypeError。省略 flush 会让测试误以为没有错误,同时丢掉这个未完成尾部的处理结果。
stream: true 也不会把所有错误推迟到末尾:实验中的 E4 41 已经构成非法组合,严格模式当次就抛错。由此可以给接收代码安排清晰的控制流:每块解码可能失败,结束解码也可能失败,两处都需要进入相同的错误处理策略。若最终才确认整条消息有效,前面已经解出的片段就不宜提前触发不可撤销的业务动作;可以先累计或暂存,再在完整校验成功后提交。
在真实数据管道里,一次逻辑文本流应拥有自己的解码状态。本文没有处理多条消息混用解码器、背压或内存上限;把样例扩展为生产代码时,仍要定义消息边界、最大长度和失败后的资源释放行为。这里的切点遍历是回归测试,不是性能基准,也不是完整的 Unicode 一致性测试。
五、传视图还是传底层 buffer,会改变输入范围
最后一组构造六个字节的载体,只让中间四个字节表示 A中,首尾各放一个非法 UTF-8 字节 FF。window 是一个子视图,它带着 byteOffset 和 byteLength;window.buffer 指向的却是完整底层存储。decode 支持 ArrayBuffer、TypedArray 和 DataView,类型范围见 Node.js 解码输入文档,下面通过明确的测试数据验证范围差异。
保存为 05_views.mjs,运行 node 05_views.mjs。成功时标准输出如下方所列;任何断言失败都会使程序退出。
import assert from 'node:assert/strict';
const carrier = Uint8Array.of(0xff, 0x41, 0xe4, 0xb8, 0xad, 0xff);
const window = carrier.subarray(1, 5);
const decoder = new TextDecoder('utf-8', { fatal: true });
assert.equal(window.byteOffset, 1);
assert.equal(window.byteLength, 4);
assert.equal(window.buffer.byteLength, 6);
assert.equal(decoder.decode(window), 'A中');
const dataView = new DataView(window.buffer, window.byteOffset, window.byteLength);
assert.equal(decoder.decode(dataView), 'A中');
const sameWindow = new Uint8Array(window.buffer, window.byteOffset, window.byteLength);
assert.equal(decoder.decode(sameWindow), 'A中');
// Wrong variant: .buffer expands the input to the entire backing storage.
assert.throws(() => decoder.decode(window.buffer), TypeError);
const wrong = new TextDecoder().decode(window.buffer);
assert.equal(wrong, '\uFFFDA中\uFFFD');
assert.notEqual(wrong, 'A中');
const copy = new Uint8Array(window);
assert.notEqual(copy.buffer, window.buffer);
assert.equal(copy.byteOffset, 0);
assert.equal(copy.byteLength, 4);
assert.equal(decoder.decode(copy), 'A中');
console.log(`offset=${window.byteOffset} windowBytes=${window.byteLength} backingBytes=${window.buffer.byteLength}`);
console.log(`window=${decoder.decode(window)}`);
console.log(`wholeBuffer=${JSON.stringify(wrong)}`);
console.log('wholeBufferFatal=TypeError');
console.log('dataViewAndExactCopy=A中');
预期标准输出:
offset=1 windowBytes=4 backingBytes=6 window=A中 wholeBuffer="�A中�" wholeBufferFatal=TypeError dataViewAndExactCopy=A中
直接传 window 能成功得到 A中;改传 window.buffer 后,严格模式报错,宽松模式还会把首尾多出来的字节显示成替换字符。这个负例说明:把视图改写成底层 buffer 并非无条件等价的类型转换。排查“同一段内容为什么突然解码失败”时,除了打印字节值,也应该打印偏移量、窗口长度和底层总长度。
如果下游需要另一种视图,重建时保留原来的 byteOffset 与 byteLength;如果需要独立存储,本例的 new Uint8Array(window) 会复制窗口内的元素。是否复制应该根据所有权和后续修改需求决定,不应为了让接口“看起来能接收”而扩大字节范围。对于从大型缓冲区切出的消息体,这个检查尤其值得成为单元测试的一部分。
把边界条件变成日常测试
这五个实验可以直接纳入项目的测试目录:既检查正确结果,也检查错误实现确实会产生不同结果。维护时优先保留混合字符样本、合法的字面替换字符、开头与正文中的 U+FEFF、跨字符分块、未完成末尾,以及带前后哨兵字节的子视图。只留下普通英文样本,会让多个不同层次的边界错误同时失去覆盖。
选择参数前先回答三个问题:输入是否必须严格合法,开头 BOM 是否应作为正文保留,这次调用是否真的代表完整输入结束。然后再核对传入的字节窗口。这样做能够把“偶尔乱码”缩小为可以复现的状态、长度和策略问题,而无需猜测编码器是否随机出错。
资料说明:本文参考上文链接的一手规范与 Node.js v24.19.0 文档,具体样本的数值、输出和负例结论均由本文程序在该版本本地执行验证。本文只讨论 UTF-8 相关行为,不将其他字符编码、特殊 Node.js 构建或未测试环境的表现当成已验证结论。

