-
-
Notifications
You must be signed in to change notification settings - Fork 77
Expand file tree
/
Copy pathjson-parse-stream.ts
More file actions
67 lines (58 loc) · 1.54 KB
/
json-parse-stream.ts
File metadata and controls
67 lines (58 loc) · 1.54 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
56
57
58
59
60
61
62
63
64
65
66
67
import { pipeline } from 'node:stream/promises'
import split2 from 'split2'
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) => {
(assembler as any)[chunk.name]?.(chunk.value)
})
stream.pipe(parser)
parser.on('end', () => {
resolve(assembler.current)
})
})
}
export async function parseJsonStreamWithConcatArrays<T, K = T>(
stream: NodeJS.ReadableStream,
processor?: (value: T) => K,
): Promise<K[]> {
const values: K[] = []
let lineNumber = 0
await pipeline(
stream,
split2(),
async (source: AsyncIterable<string>) => {
for await (const line of source) {
lineNumber += 1
if (!line) {
continue
}
try {
const parsed = JSON.parse(line) as T
const result = processor ? processor(parsed) : (parsed as unknown as K)
values.push(result)
}
catch (e) {
const preview = line.length > 256 ? `${line.slice(0, 256)}...` : line
console.warn(
`[rolldown-devtools] JSON parse stream skip bad line ${lineNumber}: ${(e as Error).message}\n${preview}`,
)
}
}
},
)
return values
}