csvtojson.js
5.21 KB
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
function csvtojson() {
var Converter = require("../v2").Converter;
var fs = require("fs");
var options = require("./options.json");
var cmds = options.commands;
var opts = options.options;
var exps = options.examples;
var pkg = require("../package.json");
var os = require("os");
/**
*{
"cmd": "parse", command to run
"options": {}, options to passe to the command
"inputStream": process.stdin // input stream for the command. default is stdin. can be a file read stream.
};
*
*/
var parsedCmd;
function _showHelp(errno) {
var key;
errno = typeof errno === "number" ? errno : 0;
console.log("csvtojson: Convert csv to JSON format");
console.log("version:", pkg.version);
console.log("Usage: csvtojson [<command>] [<options>] filepath\n");
console.log("Commands: ");
for (key in cmds) {
if (cmds.hasOwnProperty(key)) {
console.log("\t%s: %s", key, cmds[key]);
}
}
console.log("Options: ");
for (key in opts) {
if (opts.hasOwnProperty(key)) {
console.log("\t%s: %s", key, opts[key].desc);
}
}
console.log("Examples: ");
for (var i = 0; i < exps.length; i++) {
console.log("\t%s", exps[i]);
}
process.exit(errno);
}
function stringToRegExp(str) {
var lastSlash = str.lastIndexOf("/");
var source = str.substring(1, lastSlash);
var flag = str.substring(lastSlash + 1);
return new RegExp(source,flag);
}
function parse() {
var is = parsedCmd.inputStream;
if (parsedCmd.options.maxRowLength === undefined) {
parsedCmd.options.maxRowLength = 10240;
}
if (is === process.stdin && is.isTTY) {
console.log("Please specify csv file path or pipe the csv data through.\n");
_showHelp(1);
}
if (parsedCmd.options.delimiter === "\\t") {
parsedCmd.options.delimiter = "\t";
}
if (parsedCmd.options.ignoreColumns) {
parsedCmd.options.ignoreColumns=stringToRegExp(parsedCmd.options.ignoreColumns);
}
if (parsedCmd.options.includeColumns) {
parsedCmd.options.includeColumns=stringToRegExp(parsedCmd.options.includeColumns);
}
var conv = new Converter(parsedCmd.options);
var isFirst = true;
conv.on("error", function (err, pos) {
if (!parsedCmd.options.quiet) {
console.error("csvtojson got an error: ", err);
if (pos) {
console.error("The error happens at following line: ");
console.log(pos);
}
}
process.exit(1);
})
.on("data",function (dataStr) {
process.stdout.write((isFirst ? "" : "," + os.EOL) + dataStr.toString().substr(0,dataStr.length-1));
isFirst = false;
})
.on("done", function () {
console.log(os.EOL + "]");
})
console.log("[");
is.pipe(conv);
// is.pipe(conv);
}
function run(cmd, options) {
if (cmd === "parse") {
parse();
} else if (cmd === "version") {
console.log(pkg.version);
} else {
console.log("unknown command %s.", cmd);
_showHelp(1);
}
}
function commandParser() {
var parsedCmd = {
"cmd": "parse",
"options": {},
"inputStream": process.stdin
};
function parseObject(val, optional) {
try {
return JSON.parse(val);
} catch (e) {
if (optional) {
return val;
} else {
console.error(e);
process.exit(1);
}
}
}
function parseBool(str, optName) {
str = str.toLowerCase();
if (str === "true" || str === "y") {
return true;
} else if (str === "false" || str === "n") {
return false;
}
console.log("Unknown boolean value %s for parameter %s.", str, optName);
_showHelp(1);
}
process.argv.slice(2).forEach(function (item) {
if (item.indexOf("--") > -1) {
var itemArr = item.split("=");
var optName = itemArr[0];
var key, val, type;
if (!opts[optName]) {
console.log("Option %s not supported.", optName);
_showHelp(1);
}
key = optName.replace('--', '');
val = itemArr[1] || '';
type = opts[optName].type;
if (type === "string") {
parsedCmd.options[key] = val.toString();
} else if (type === "boolean") {
parsedCmd.options[key] = parseBool(val, optName);
} else if (type === "number") {
parsedCmd.options[key] = parseFloat(val);
} else if (type === "object") {
parsedCmd.options[key] = parseObject(val, false);
} else if (type === "~object") {
parsedCmd.options[key] = parseObject(val, true);
} else {
throw ({
name: "UnimplementedException",
message: "Option type parsing not implemented. See bin/options.json"
});
}
} else if (cmds[item]) {
parsedCmd.cmd = item;
} else if (fs.existsSync(item)) {
parsedCmd.inputStream = fs.createReadStream(item);
} else {
console.log("unknown parameter %s.", item);
}
});
return parsedCmd;
}
process.stdin.setEncoding('utf8');
parsedCmd = commandParser();
run(parsedCmd.cmd, parsedCmd.options);
}
module.exports = csvtojson;
if (!module.parent) {
csvtojson();
}