UNPKG

2 kBJavaScriptView Raw
1// cli.js
2
3var fs = require("fs");
4var Stream = require("stream");
5var msgpack = require("../");
6
7exports.CLI = CLI;
8
9function help() {
10 var cfgmap = {
11 "M": "input MessagePack (default)",
12 "J": "input JSON",
13 "m": "output MessagePack (default)",
14 "j": "output JSON",
15 "h": "show help message",
16 "1": "add spacer for JSON"
17 };
18 process.stderr.write("Usage: msgpack-lite -[flags] [infile] [outfile]\n");
19 Object.keys(cfgmap).forEach(function(key) {
20 process.stderr.write(" -" + key + " " + cfgmap[key] + "\n");
21 });
22 process.exit(1);
23}
24
25function CLI() {
26 var input;
27 var pass = new Stream.PassThrough({objectMode: true});
28 var output;
29
30 var args = {};
31 Array.prototype.forEach.call(arguments, function(val) {
32 if (val[0] === "-") {
33 val.split("").forEach(function(c) {
34 args[c] = true;
35 });
36 } else if (!input) {
37 input = val;
38 } else {
39 output = val;
40 }
41 });
42
43 if (args.h) return help();
44 if (!Object.keys(args).length) return help();
45
46 if (input === "-") input = null;
47 if (output === "-") output = null;
48 input = input ? fs.createReadStream(input) : process.stdin;
49 output = output ? fs.createWriteStream(output) : process.stdout;
50
51 if (args.j) {
52 encodeJSON(pass, output);
53 } else {
54 pass.pipe(msgpack.createEncodeStream()).pipe(output);
55 }
56
57 if (args.J) {
58 decodeJSON(input, pass);
59 } else {
60 input.pipe(msgpack.createDecodeStream()).pipe(pass);
61 }
62}
63
64function encodeJSON(input, output) {
65 input.on("data", function(data) {
66 output.write(JSON.stringify(data) + "\n");
67 });
68}
69
70function decodeJSON(input, output) {
71 var buf = "";
72 input.on("data", function(chunk) {
73 buf += chunk;
74 check(true);
75 });
76 input.on("end", function() {
77 check();
78 });
79 function check(leave) {
80 var list = buf.split("\n");
81 if (list.length < 2) return;
82 if (leave) buf = list.pop();
83 list.forEach(function(str) {
84 if (!str.length) return;
85 output.write(JSON.parse(str));
86 });
87 }
88}
\No newline at end of file