forked from antonmedv/fx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stream.js
84 lines (72 loc) · 1.55 KB
/
stream.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
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
'use strict'
const JSON = require('lossless-json')
function apply(cb, input) {
let json
try {
json = JSON.parse(input)
} catch (e) {
process.stderr.write(e.toString() + '\n')
return
}
cb(json)
}
function stream(from, cb) {
let buff = ''
let lastChar = ''
let len = 0
let depth = 0
let isString = false
let count = 0
let head = ''
const check = (i) => {
if (depth <= 0) {
const input = buff.substring(0, len + i + 1)
if (count > 0) {
if (head !== '') {
apply(cb, head)
head = ''
}
apply(cb, input)
} else {
head = input
}
buff = buff.substring(len + i + 1)
len = -i - 1
count++
}
}
return {
isStream() {
return count > 1
},
value() {
return head + buff
},
read() {
let chunk
while ((chunk = from.read())) {
len = buff.length
buff += chunk
for (let i = 0; i < chunk.length; i++) {
if (isString) {
if (chunk[i] === '"' && ((i === 0 && lastChar !== '\\') || (i > 0 && chunk[i - 1] !== '\\'))) {
isString = false
check(i)
}
continue
}
if (chunk[i] === '{' || chunk[i] === '[') {
depth++
} else if (chunk[i] === '}' || chunk[i] === ']') {
depth--
check(i)
} else if (chunk[i] === '"') {
isString = true
}
}
lastChar = chunk[chunk.length - 1]
}
}
}
}
module.exports = stream