-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathjsonl-stream.ts
More file actions
52 lines (45 loc) · 1.17 KB
/
jsonl-stream.ts
File metadata and controls
52 lines (45 loc) · 1.17 KB
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
49
50
51
52
import { Writable } from "node:stream";
/**
* Safely parses a JSON string, returning null if parsing fails.
* @param str - The JSON string to parse.
* @returns The parsed object or null if invalid.
*/
export function safeJsonParse(str: string): unknown {
try {
return JSON.parse(str);
} catch {
return undefined;
}
}
/**
* Writable stream that buffers data until a newline,
* parses each line as JSON, and emits the parsed object.
*/
export class JsonlStream extends Writable {
constructor() {
let buffer = "";
super({
write: (chunk, _encoding, callback) => {
buffer += String(chunk);
let newlineIndex = buffer.indexOf("\n");
while (newlineIndex !== -1) {
const line = buffer.substring(0, newlineIndex).trim();
buffer = buffer.substring(newlineIndex + 1);
const json = safeJsonParse(line);
if (json !== undefined) {
this.emit("json", json);
}
newlineIndex = buffer.indexOf("\n");
}
callback();
},
});
}
/**
* Registers a listener for parsed JSON objects.
* @param listener - Function called with each parsed object.
*/
onJson(callback: (json: unknown) => void) {
this.on("json", callback);
}
}