实现说明
结构是循环套循环:for await (const line of rl) 在外,for (const [line, count] of counts) 在内。异步流被 await 线性化,失败处理保持局部。createReadStream、writeFileSync、createInterface 来自 node:fs、node:readline——Node.js 随运行时自带的核心模块。
演示用的数据放在这几个模块级绑定中:rl、counts。
使用要点
- 依赖面只有
node:fs,而它内置于 Node.js。 - 直接运行文件,输出会带上标签,比如
lines counted:——输出的每一行都能指回产生它的那次调用。
常见问题
需要安装第三方包吗?
不需要——node:fs 是 Node.js 内建模块,无需安装。
核心语句
counts.set(line, (counts.get(line) ?? 0) + 1);
const counts = new Map();
代码示例
import { createReadStream, writeFileSync } from 'node:fs';
import { createInterface } from 'node:readline';
// seed a small log file for the demo
writeFileSync('events.log', ['boot ok', 'cache cold', 'boot ok'].join('\n'), 'utf8');
// readline over a read stream hands out one line per iteration,
// so the file never has to fit in memory at once
const rl = createInterface({ input: createReadStream('events.log') });
const counts = new Map();
for await (const line of rl) {
counts.set(line, (counts.get(line) ?? 0) + 1);
}
console.log('lines counted:', [...counts.values()].reduce((a, b) => a + b, 0));
for (const [line, count] of counts) {
console.log(`${count}x ${line}`);
}