UNPKG

2.35 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 "S": "input JSON(s) '\\n' separated stream",
14 "m": "output MessagePack (default)",
15 "j": "output JSON(s)",
16 "h": "show help message",
17 "1": "add a spacer for JSON output"
18 };
19 var keys = Object.keys(cfgmap);
20 var flags = keys.join("");
21 process.stderr.write("Usage: msgpack-lite [-" + flags + "] [infile] [outfile]\n");
22 keys.forEach(function(key) {
23 process.stderr.write(" -" + key + " " + cfgmap[key] + "\n");
24 });
25 process.exit(1);
26}
27
28function CLI() {
29 var input;
30 var pass = new Stream.PassThrough({objectMode: true});
31 var output;
32
33 var args = {};
34 Array.prototype.forEach.call(arguments, function(val) {
35 if (val[0] === "-") {
36 val.split("").forEach(function(c) {
37 args[c] = true;
38 });
39 } else if (!input) {
40 input = val;
41 } else {
42 output = val;
43 }
44 });
45
46 if (args.h) return help();
47 if (!Object.keys(args).length) return help();
48
49 if (input === "-") input = null;
50 if (output === "-") output = null;
51 input = input ? fs.createReadStream(input) : process.stdin;
52 output = output ? fs.createWriteStream(output) : process.stdout;
53
54 if (args.j) {
55 var spacer = args[2] ? " " : args[1] ? " " : null;
56 pass.on("data", function(data) {
57 output.write(JSON.stringify(data, null, spacer) + "\n");
58 });
59 } else {
60 // pass.pipe(msgpack.createEncodeStream()).pipe(output);
61 pass.on("data", function(data) {
62 output.write(msgpack.encode(data));
63 });
64 }
65
66 if (args.J || args.S) {
67 decodeJSON(input, pass, args);
68 } else {
69 input.pipe(msgpack.createDecodeStream()).pipe(pass);
70 }
71}
72
73function decodeJSON(input, output, args) {
74 var buf = "";
75 input.on("data", function(chunk) {
76 buf += chunk;
77 if (args.S) sendStreaming();
78 });
79 input.on("end", function() {
80 sendAll();
81 });
82
83 function sendAll() {
84 if (!buf.length) return;
85 output.write(JSON.parse(buf));
86 }
87
88 function sendStreaming(leave) {
89 var list = buf.split("\n");
90 buf = list.pop();
91 list.forEach(function(str) {
92 str = str.replace(/,\s*$/, "");
93 if (!str.length) return;
94 output.write(JSON.parse(str));
95 });
96 }
97}
\No newline at end of file