Node.js 流式统计 JSONL 日志:中文跨块也能正确读取
日志文件比较大时,先 readFile 再按换行切分,会把整个文件读进内存。对于一行一条记录的 JSONL,可以边读边统计;但文件读取的块边界不一定恰好落在换行处,也可能把一个中文字符的 UTF-8 字节拆开。如果对每个块单独调用 chunk.toString('utf8'),被拆开的字符可能变成 �。
下面用 Node.js 内置模块统计日志的 level,不安装第三方包。示例只处理 UTF-8 JSONL 文件,实际在 Windows 11、Node.js v22.22.0 下运行,未做线上压测。
实现:保留未完成的字符和行
将下列代码保存为 jsonl-stats.cjs。流式 TextDecoder 负责跨块解码,pending 保存尚未遇到换行符的文本;读完时再调用一次 decode(),处理末尾可能残留的字节。
const { createReadStream } = require('node:fs');
const { TextDecoder } = require('node:util');
async function* readJsonl(input) {
const decoder = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });
let pending = '';
let lineNumber = 0;
function parse(line) {
lineNumber++;
let record;
try {
record = JSON.parse(line);
} catch (error) {
throw new Error(`第 ${lineNumber} 行:无效 JSON (${error.message})`);
}
if (record === null || typeof record !== 'object' || Array.isArray(record)) {
throw new Error(`第 ${lineNumber} 行:必须是 JSON 对象`);
}
return record;
}
for await (const chunk of input) {
pending += decoder.decode(chunk, { stream: true });
let newline;
while ((newline = pending.indexOf('\n')) !== -1) {
const line = pending.slice(0, newline);
pending = pending.slice(newline + 1);
yield parse(line);
}
}
pending += decoder.decode();
if (pending) yield parse(pending);
}
async function summarize(input) {
const counts = { total: 0, info: 0, warn: 0, error: 0, other: 0 };
for await (const record of readJsonl(input)) {
counts.total++;
const key = ['info', 'warn', 'error'].includes(record.level) ? record.level : 'other';
counts[key]++;
}
return counts;
}
module.exports = { summarize, readJsonl };
if (require.main === module) {
(async () => {
if (process.argv.length !== 3) throw new Error('用法:node jsonl-stats.cjs 文件路径');
const result = await summarize(createReadStream(process.argv[2]));
console.log(JSON.stringify(result, null, 2));
})().catch((error) => {
console.error(error.message);
process.exitCode = 1;
});
}
fatal: true 让非法或截断的 UTF-8 报错,而不是静默替换。这里的 ignoreBOM: true 名字有点反直觉:它会保留解码出的 BOM;文件开头若有 BOM,JSON.parse 就会拒绝,符合 JSON Lines 不允许 BOM 的要求。它不会拒绝 JSON 字符串内合法的 U+FEFF 字符。
准备样例并运行
将下面内容保存为 UTF-8 无 BOM 的 sample.jsonl,与代码放在同一目录:
{"level":"info","message":"启动成功"}
{"level":"warn","message":"磁盘空间不足"}
{"level":"error","message":"连接失败"}
{"level":"info","message":"重试成功"}
{"level":"debug","message":"耗时 42 毫秒"}
在该目录执行(需要 node 命令可用):
node jsonl-stats.cjs sample.jsonl
实际输出:
{
"total": 5,
"info": 2,
"warn": 1,
"error": 1,
"other": 1
}
边界与取舍
- 支持 LF、CRLF,以及最后一行没有换行符;空文件返回各项均为 0。空行、只有空白的行或无效 JSON 会报所在行号,程序返回非零退出码,不输出部分统计结果。
- JSON Lines 本身允许任意 JSON 值;这个日志示例额外要求每行是对象。
level只识别大小写完全匹配的info、warn、error,其他值或缺失字段计入other。 - 程序不会把全部记录存入数组,但仍需缓冲当前未结束的行和当前读入的数据块,还要构造当前解析出的对象。它不是固定内存上限:单行极大或没有换行符时,内存仍可能增长;对于不可信输入,应另行设置单行字节限制。
- 非法 UTF-8 会终止处理,但解码器可能一次接收多行数据,错误信息不保证能定位到具体行;这里也不处理压缩文件、自动跳过坏行或持续追踪追加日志。
测试
将下面代码保存为 jsonl-stats.test.cjs,与实现文件放在一起。测试会在系统临时目录创建并清理测试文件,不修改你的日志。
const { test } = require('node:test');
const assert = require('node:assert/strict');
const { Readable } = require('node:stream');
const { spawnSync } = require('node:child_process');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { summarize, readJsonl } = require('./jsonl-stats.cjs');
const source = (text) => Readable.from([Buffer.from(text)]);
test('按 level 汇总每条记录', async () => {
const result = await summarize(source('{"level":"info"}\n{"level":"error"}\n'));
assert.deepEqual(result, { total: 2, info: 1, warn: 0, error: 1, other: 0 });
});
test('逐字节切块也能解析多字节中文、CRLF 和无换行尾行', async () => {
const bytes = Buffer.from('{"level":"info","msg":"中文😀"}\r\n{"level":"warn"}');
const input = Readable.from(Array.from(bytes, (byte) => Buffer.from([byte])));
const records = [];
for await (const record of readJsonl(input)) records.push(record);
assert.deepEqual(records, [{ level: 'info', msg: '中文😀' }, { level: 'warn' }]);
});
test('空行和无效 JSON 报告实际行号', async () => {
for (const badLine of ['', '{坏}']) {
await assert.rejects(
summarize(source(`{"level":"info"}\n${badLine}\n`)),
/第 2 行:无效 JSON/
);
}
});
test('只接受对象,未知或缺失 level 归 other', async () => {
const result = await summarize(source('{"level":"trace"}\n{}\n{"level":3}\n'));
assert.deepEqual(result, { total: 3, info: 0, warn: 0, error: 0, other: 3 });
for (const value of ['null', '[]', '3', '"str"']) {
await assert.rejects(summarize(source(`${value}\n`)), /第 1 行:必须是 JSON 对象/);
}
});
test('逐字节拆分的 UTF-8 BOM 按 JSON Lines 格式拒绝', async () => {
const bytes = Buffer.from('\ufeff{"level":"info"}\n');
const input = Readable.from(Array.from(bytes, (byte) => Buffer.from([byte])));
await assert.rejects(summarize(input), /第 1 行:无效 JSON/);
});
test('命令行读真实文件并在失败时返回非零状态', () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'jsonl-stats-test-'));
try {
const script = path.join(__dirname, 'jsonl-stats.cjs');
const file = path.join(dir, 'data.jsonl');
fs.writeFileSync(file, '{"level":"warn"}\n{"level":"error"}');
const good = spawnSync(process.execPath, [script, file], { encoding: 'utf8' });
assert.equal(good.status, 0);
assert.deepEqual(JSON.parse(good.stdout), { total: 2, info: 0, warn: 1, error: 1, other: 0 });
const missing = spawnSync(process.execPath, [script, path.join(dir, 'missing.jsonl')], { encoding: 'utf8' });
assert.equal(missing.status, 1);
assert.equal(missing.stdout, '');
const usage = spawnSync(process.execPath, [script], { encoding: 'utf8' });
assert.equal(usage.status, 1);
assert.match(usage.stderr, /用法/);
fs.writeFileSync(file, '{}\n\n');
const invalid = spawnSync(process.execPath, [script, file], { encoding: 'utf8' });
assert.equal(invalid.status, 1);
assert.equal(invalid.stdout, '');
assert.match(invalid.stderr, /第 2 行/);
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
});
test('坏 UTF-8(包括截断的多字节字符)会失败', async () => {
for (const bytes of [
Buffer.from([0x7b, 0xff, 0x7d, 0x0a]),
Buffer.from([0x7b, 0x22, 0x61, 0x22, 0x3a, 0x22, 0xe4])
]) {
await assert.rejects(summarize(Readable.from([bytes])), /utf-8/i);
}
});
执行:
node --test jsonl-stats.test.cjs
本次运行结果:7 项测试通过,0 项失败。测试包含逐字节切块、中文与 emoji、CRLF、无换行尾行、坏数据、BOM 和命令行错误路径。
参考资料:JSON Lines 官方格式说明、Node.js 官方 TextDecoder 文档。
本文由 AI 协助撰写、生成示例和测试;文中运行结果来自上述本地环境的实际执行。
- 点赞
- 收藏
- 关注作者
评论(0)