-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
executable file
·98 lines (84 loc) · 2.4 KB
/
index.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
const { EventEmitter } = require("events");
const Parser = require("./lib/Parser.js");
const Renderer = require("./lib/Renderer.js");
/**
* TODO
*
* @event JSONStream#data
*/
/**
* TODO
*
* @event JSONStream#drain
*/
/**
* TODO
*
* @event JSONStream#end
*/
/**
* Class representing a JSONStream.
*
* @augments EventEmitter
*/
class JSONStream extends EventEmitter {
/**
* Constructor
*
* @param {object} [opts={}] - Options, @see {@link Renderer#constructor}
*/
constructor(opts={}) {
super();
this.parser = new Parser();
this.renderer = new Renderer(opts);
this.parser.on("end", () => this.emit("end"));
this.parser.on("drain", () => this.emit("drain"));
this.parser.on("token", (token) => this.renderer.render_token(token));
this.renderer.on("data", (string) => this.emit("data",string));
}
/**
* Write a chunk of data to the stream.
*
* @param {string} string - The chunk of data to write.
* @returns {Promise} Resolves when the chunk has been written.
*/
async write(string) { return this.parser.write(string); }
/**
* Write a chunk of data to the stream, then close it
*
* @param {string} string - The chunk of data to write.
* @returns {Promise} Resolves when the stream has been closed
*/
async end(string="") { return this.parser.end(string); }
/**
* Statically parse a JSON string.
*
* @param {string} string - The JSON string to parse.
* @param {object} [opts={}] - Options, @see {@link Renderer#constructor}
* @returns {string} The parsed JSON string.
*/
static parse(string, opts={}) {
const sp = new JSONStream(opts);
let out = "";
sp.on("data", (chunk) => out += chunk);
return sp.end(string).then(() => out);
}
/**
* Statically parse a javascript object into a JSON string.
*
* @param {object|Array} object - The javascript object to parse
* @param {object} [opts={}] - Options, @see {@link Renderer#constructor}
* @returns {string} The parsed JSON string.
*/
static stringify(object, opts={}) {
const sp = new JSONStream(opts);
let out = "";
sp.on("data", (chunk) => out += chunk);
return sp.end(JSON.stringify(object)).then(() => out);
}
}
module.exports = exports = {
JSONStream,
Parser,
Renderer
};