-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjsuck.js
89 lines (71 loc) · 2.6 KB
/
jsuck.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
85
86
87
88
89
const clarinet = require("clarinet");
const Stream = require("stream");
class streamJson extends Stream.Transform {
constructor(options = {}) {
super({ objectMode: true, highWaterMark: options.highWaterMark || 1 })
this.clarinet = clarinet.createStream();
this.states = [];
this.list = [];
this.clarinet.on("error", this.emit.bind(this, "error"));
this.clarinet.on("value", function(val) {
if (this.states[this.states.length-1] === "array") {
this.list[this.list.length-1].push(val);
} else if (this.states[this.states.length-1] === "object") {
this.list[this.list.length-1][this.key] = val;
delete this.key;
}
}.bind(this));
this.clarinet.on("key", function(key) {
if (this.states[this.states.length-1] === "object") {
this.key = key;
}
}.bind(this));
this.clarinet.on("openobject", function(key) {
var val = {};
if (this.states[this.states.length-1] === "array") {
this.list[this.list.length-1].push(val);
} else if (this.states[this.states.length-1] === "object") {
this.list[this.list.length-1][this.key] = val;
delete this.key;
}
this.list.push(val);
this.states.push("object");
if (key) {
this.key = key;
}
}.bind(this));
this.clarinet.on("closeobject", function() {
var o = this.list.pop();
this.states.pop();
if (this.list.length === 0) {
this.push(o);
}
}.bind(this));
this.clarinet.on("openarray", function() {
var val = [];
if (this.states[this.states.length-1] === "array") {
this.list[this.list.length-1].push(val);
} else if (this.states[this.states.length-1] === "object") {
this.list[this.list.length-1][this.key] = val;
delete this.key;
}
this.list.push(val);
this.states.push("array");
}.bind(this));
this.clarinet.on("closearray", function() {
var o = this.list.pop();
this.states.pop();
if (this.list.length === 0) {
this.push(o);
}
}.bind(this));
}
_transform(input, encoding, done) {
if (this.clarinet.write(input)) {
return done();
} else {
this.clarinet.once("drain", done);
}
};
}
module.exports = streamJson