-
Notifications
You must be signed in to change notification settings - Fork 130
/
Copy pathcli.js
97 lines (85 loc) · 2.29 KB
/
cli.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
// cli.js
var fs = require("fs");
var Stream = require("stream");
var msgpack = require("../");
exports.CLI = CLI;
function help() {
var cfgmap = {
"M": "input MessagePack (default)",
"J": "input JSON",
"S": "input JSON(s) '\\n' separated stream",
"m": "output MessagePack (default)",
"j": "output JSON(s)",
"h": "show help message",
"1": "add a spacer for JSON output"
};
var keys = Object.keys(cfgmap);
var flags = keys.join("");
process.stderr.write("Usage: msgpack-lite [-" + flags + "] [infile] [outfile]\n");
keys.forEach(function(key) {
process.stderr.write(" -" + key + " " + cfgmap[key] + "\n");
});
process.exit(1);
}
function CLI() {
var input;
var pass = new Stream.PassThrough({objectMode: true});
var output;
var args = {};
Array.prototype.forEach.call(arguments, function(val) {
if (val[0] === "-") {
val.split("").forEach(function(c) {
args[c] = true;
});
} else if (!input) {
input = val;
} else {
output = val;
}
});
if (args.h) return help();
if (!Object.keys(args).length) return help();
if (input === "-") input = null;
if (output === "-") output = null;
input = input ? fs.createReadStream(input) : process.stdin;
output = output ? fs.createWriteStream(output) : process.stdout;
if (args.j) {
var spacer = args[2] ? " " : args[1] ? " " : null;
pass.on("data", function(data) {
output.write(JSON.stringify(data, null, spacer) + "\n");
});
} else {
// pass.pipe(msgpack.createEncodeStream()).pipe(output);
pass.on("data", function(data) {
output.write(msgpack.encode(data));
});
}
if (args.J || args.S) {
decodeJSON(input, pass, args);
} else {
input.pipe(msgpack.createDecodeStream()).pipe(pass);
}
}
function decodeJSON(input, output, args) {
var buf = "";
input.on("data", function(chunk) {
buf += chunk;
if (args.S) sendStreaming();
});
input.on("end", function() {
sendAll();
});
function sendAll() {
if (!buf.length) return;
output.write(JSON.parse(buf));
}
function sendStreaming(leave) {
var list = buf.split("\n");
buf = list.pop();
list.forEach(function(str) {
str = str.replace(/,\s*$/, "");
if (!str.length) return;
output.write(JSON.parse(str));
});
}
}