-
-
Notifications
You must be signed in to change notification settings - Fork 81
Expand file tree
/
Copy pathjson-parse-stream.ts
More file actions
55 lines (49 loc) · 1.25 KB
/
json-parse-stream.ts
File metadata and controls
55 lines (49 loc) · 1.25 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
53
54
55
import StreamJSON from 'stream-json'
import Assembler from 'stream-json/Assembler'
export class JsonParseStreamError extends Error {
constructor(
message: string,
public data: any,
) {
super(message)
}
}
export function parseJsonStream<T>(
stream: NodeJS.ReadableStream,
): Promise<T> {
const assembler = new Assembler()
const parser = StreamJSON.parser()
return new Promise<T>((resolve) => {
parser.on('data', (chunk) => {
// @ts-expect-error casting
assembler[chunk.name]?.(chunk.value)
})
stream.pipe(parser)
parser.on('end', () => {
resolve(assembler.current)
})
})
}
export function parseJsonStreamWithConcatArrays<T, K = T>(
stream: NodeJS.ReadableStream,
processor?: (value: T) => K,
): Promise<K[]> {
const assembler = new Assembler()
const parser = StreamJSON.parser({
jsonStreaming: true,
})
const values: K[] = []
return new Promise<K[]>((resolve) => {
parser.on('data', (chunk) => {
// @ts-expect-error casting
assembler[chunk.name]?.(chunk.value)
if (assembler.done) {
values.push(processor ? processor(assembler.current) : assembler.current)
}
})
stream.pipe(parser)
parser.on('end', () => {
resolve(values)
})
})
}