parser.js
877 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/**
* NDJSON 流解析器
*
* 处理 TCP 流中的换行分隔 JSON 消息
*/
class NDJSONParser {
constructor() {
this.buffer = '';
}
/**
* 输入数据块,返回解析出的消息数组
*/
parse(chunk) {
this.buffer += chunk.toString();
const lines = this.buffer.split('\n');
this.buffer = lines.pop(); // 保留不完整的行
const messages = [];
for (const line of lines) {
if (!line.trim()) continue;
try {
messages.push(JSON.parse(line));
} catch (e) {
// 非 JSON 行,作为原始输出
messages.push({ _raw: true, content: line });
}
}
return messages;
}
/**
* 清空缓冲区
*/
reset() {
this.buffer = '';
}
/**
* 获取剩余的缓冲区内容
*/
getRemaining() {
return this.buffer;
}
}
module.exports = { NDJSONParser };