/
pushJSON.js
255 lines (237 loc) · 6.43 KB
/
pushJSON.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
/**
* Serialize an object to JSON by pushing it to a writeable stream in little bits
*/
var Readable = require('stream').Readable ;
var DEBUG = global.DEBUG || (process.env.DEV ? function(){ console.log.apply(this,arguments); }:function(){}) ;
function iter(fn) {
return function() {
while (fn = fn()) ;
}
}
function createReadStream(obj,replacer,onComplete) {
var rs = new Readable ;
var readyToRead = null ;
var remaining = 1024 ; // Small buffer to get going, then start yielding
var chunk = [] ;
var t = Date.now() ;
var j = writeInChunks(function(data,done){
remaining = remaining-data.length ;
chunk.push(data) ;
if (done) {
if (remaining>0)
return done ;
readyToRead = iter(done) ;
rs.push(chunk.join("")) ;
chunk = [] ;
}
return ;
},obj,replacer,function(){
if (chunk.length)
rs.push(chunk.join("")) ;
chunk = null ;
rs.push(null) ;
DEBUG(1,"PushJSON t="+(Date.now()-t)) ;
onComplete && onComplete() ;
}) ;
rs._read = function(size) {
remaining = size ;
var x = readyToRead ;
readyToRead = null ;
x && setImmediate(x) ;
}
return rs ;
}
function writeInChunks(out,obj,replacer,onComplete) {
(function(){
// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.
var enc = "utf8";
if (obj===undefined)
return "" ;
// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.
var xform ;
if (replacer==null) {
xform = function(parent,k,o) {
if (o && typeof o === 'object' && typeof o.toJSON === 'function') {
o = o.toJSON(k);
}
return o ;
}
}else if (typeof replacer === 'function'){
xform = function(parent,k,o) {
if (o && typeof o === 'object' && typeof o.toJSON === 'function') {
o = o.toJSON(k);
}
return replacer.call(parent,k,o) ;
}
} else if (Array.isArray(replacer)) {
if (o && typeof o === 'object' && typeof o.toJSON === 'function') {
o = o.toJSON(k);
}
// Do something with replacer
//return replacer.call(parent,k,o) ;
return o ;
} else throw new Error("Replacer must be nullish, a function or an Array") ;
var stack = [] ;
var t = Date.now() ;
var next = function(){
t = Date.now()-t ;
//console.log("serialized in "+t+"ms") ;
onComplete()
};
var index = 0 ;
var sep ;
var sendChunk ;
var yield = 0 ;
if (typeof out==="function")
sendChunk = out ;
else if (out.write.length==3) {
// Support "callback"
sendChunk = function(data,done) {
// Some of the streams (e.g. process.stdout) support the callback,
// but use process.nextTick() to invoke it, meaning we run out of
// stack, so we still yield occasionally so it unwinds. Ideally,
// we'd simply be pulled by the stream, but it doesn't seem to
// want to play nice.
yield = yield+data.length ;
if (done) {
if (yield<8192) {
out.write(data,enc,done && iter(done)) ;
} else {
yield = 0 ;
setImmediate(iter(done)) ;
}
} else {
out.write(data,enc) ;
}
}
} else {
// No callback
sendChunk = function(data,done) {
yield = yield+data.length ;
if (done) {
if (out.write(data,enc)) {
if (yield<8192)
return done ;
yield = 0 ;
setImmediate(iter(done)) ;
return ;
}
out.once('drain',iter(done)) ;
return ;
}
out.write(data,enc) ;
return ;
}
}
function walk() {
if (obj==null) {
return sendChunk('null',next);
} else if (typeof obj === "string") {
return sendChunk(quote(obj),next);
} else if (typeof obj !== "object" || obj instanceof Number) {
//return sendChunk(JSON.stringify(obj),next);
return sendChunk(obj.toString(),next);
} else if (Array.isArray(obj)) {
if (obj.length==0)
return sendChunk('[]',next);
else {
// Save state
stack.push({next:next,index:index,obj:obj}) ;
// Current obj
index = 0 ;
function stepArray() {
var peek = stack[stack.length-1] ;
if (index<peek.obj.length) {
obj = peek.obj[index] ;
obj = xform(peek.obj,index,obj) ;
index += 1 ;
sendChunk(sep);
sep = ", " ;
return walk ;
} else {
sendChunk(']');
var pop = stack.pop() ;
obj = pop.obj ;
index = pop.index ;
next = pop.next ;
return next ;
}
}
sep = "[" ;
next = stepArray ;
return next ;
}
} else {
var keys = Object.keys(obj) ;
if (!keys || !keys.length) {
return sendChunk('{}',next);
}
obj = {keys:keys,v:obj} ;
// Save state
stack.push({next:next,index:index,obj:obj}) ;
// Current obj
index = 0 ;
function stepObject() {
var peek = stack[stack.length-1] ;
if (index<peek.obj.keys.length) {
var k2 = peek.obj.keys[index] ;
obj = peek.obj.v[k2] ;
obj = xform(peek.obj.v,k2,obj) ;
index += 1 ;
if (obj===undefined) {
return next ;
}
sendChunk(sep+quote(k2)+":");
sep = ", " ;
return walk ;
} else {
var pop = stack.pop() ;
obj = pop.obj ;
index = pop.index ;
next = pop.next ;
sendChunk('}');
return next ;
}
}
sep = "{" ;
next = stepObject ;
return next ;
}
}
obj = xform(null,'',obj) ;
iter(walk)() ;
})() ;
};
var escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
var meta = { // table of character substitutions
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
};
function quote(string) {
// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.
escapable.lastIndex = 0;
return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
var c = meta[a];
return typeof c === 'string'
? c
: '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
}) + '"' : '"' + string + '"';
}
module.exports = {
writeToStream:writeInChunks,
Readable:createReadStream,
continueSending:iter,
} ;