index.js
1.69 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
/*
db.collection.find().stream().pipe(Stringify()).pipe(res)
*/
var Transform = require('readable-stream/transform')
var stringify = require('json-stringify-safe')
var util = require('util')
util.inherits(Stringify, Transform)
module.exports = Stringify
function Stringify(options) {
if (!(this instanceof Stringify))
return new Stringify(options || {})
if (options && options.replacer) {
this.replacer = options.replacer;
}
if (options && options.space !== undefined) {
this.space = options.space;
}
Transform.call(this, options || {})
this._writableState.objectMode = true
// Array Deliminator and Stringifier defaults
var opener = options && options.opener ? options.opener : '[\n'
var seperator = options && options.seperator ? options.seperator : '\n,\n'
var closer = options && options.closer ? options.closer : '\n]\n'
var stringifier = options && options.stringifier ? options.stringifier : stringify
// Array Deliminators and Stringifier
this.opener = new Buffer(opener, 'utf8')
this.seperator = new Buffer(seperator, 'utf8')
this.closer = new Buffer(closer, 'utf8')
this.stringifier = stringifier
}
// Flags
Stringify.prototype.started = false
// JSON.stringify options
Stringify.prototype.replacer = null
Stringify.prototype.space = 0
Stringify.prototype._transform = function (doc, enc, cb) {
if (this.started) {
this.push(this.seperator)
} else {
this.push(this.opener)
this.started = true
}
doc = this.stringifier(doc, this.replacer, this.space)
this.push(new Buffer(doc, 'utf8'))
cb()
}
Stringify.prototype._flush = function (cb) {
if (!this.started) this.push(this.opener)
this.push(this.closer)
this.push(null)
cb()
}