实现说明
在这里做循环的是 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 }));