-
Notifications
You must be signed in to change notification settings - Fork 6
/
streamify.js
63 lines (50 loc) · 1.44 KB
/
streamify.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
//
// Pretty much all written by James Halliday (substack.net)
// Small bits by David Trejo (dtrejo.com)
//
var Traverse = require('traverse')
, fs = require('fs')
;
// emit is a function
// also, this is a sync function
exports.streamify = function streamify(obj, emit) {
Traverse(obj).forEach(function to_s (node) {
if (Array.isArray(node)) {
this.before(function () { emit('['); });
this.post(function (child) {
if (!child.isLast) emit(',');
});
this.after(function () { emit(']'); });
} else if (typeof node == 'object') {
this.before(function () { emit('{'); });
this.pre(function (x, key) {
to_s(key);
emit(':');
});
this.post(function (child) {
if (!child.isLast) emit(',');
});
this.after(function () { emit('}'); });
} else if (typeof node == 'string') {
emit(JSON.stringify(node));
} else if (typeof node == 'function') {
emit('null');
} else if (node.toString) {
emit(node.toString());
} else {
emit(node);
}
});
};
exports.streamingWrite = function streamingWrite(path, object, cb) {
var stream = fs.createWriteStream(path, { flags: 'w+', encoding: 'utf8' });
if (cb) {
stream.on('close', cb);
stream.on('error', cb);
}
exports.streamify(object, function(chunk) {
stream.write(chunk);
});
// all writes have been sent, b/c streamify is a sync function.
stream.end();
};