-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
35 lines (32 loc) · 931 Bytes
/
index.js
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
const { Transform } = require('node:stream')
const JSONStream = (opts = {}) => new Transform({
...opts,
writableObjectMode: false,
readableObjectMode: true,
transform (data, encoding, done) {
if (!Buffer.isBuffer(data)) data = Buffer.from(data);
if (this._buffer) {
data = Buffer.concat([this._buffer, data]);
}
let ptr = 0
let start = 0
while (++ptr <= data.length) {
if (data[ptr] === 10 || ptr === data.length) {
let line = ''
try {
line = JSON.parse(data.slice(start, ptr))
}
catch (error) { }
if (line) {
this.push(line)
line = null
}
if (data[ptr] === 10) start = ++ptr
}
}
this._buffer = data.slice(start)
opts?.async ? setImmediate(done) : done()
}
})
module.exports = JSONStream
JSONStream.JSONStream = JSONStream