1 | #!/usr/bin/env node
|
2 |
|
3 | 'use strict'
|
4 |
|
5 | var createReadStream = require('fs').createReadStream
|
6 | var createWriteStream = require('fs').createWriteStream
|
7 | var PassThrough = require('stream').PassThrough
|
8 |
|
9 | var eventToPromise = require('promise-toolbox/fromEvent')
|
10 | var minimist = require('minimist')
|
11 | var pump = require('pump')
|
12 |
|
13 | var csv2json = require('./')
|
14 | var pkg = require('./package.json')
|
15 |
|
16 |
|
17 |
|
18 | function createInputStream (path) {
|
19 | return path === undefined || path === '-'
|
20 | ? process.stdin
|
21 | : createReadStream(path)
|
22 | }
|
23 |
|
24 | function createOutputStream (path) {
|
25 | if (path !== undefined && path !== '-') {
|
26 | return createWriteStream(path)
|
27 | }
|
28 |
|
29 |
|
30 | var stream = new PassThrough()
|
31 | stream.pipe(process.stdout)
|
32 | return stream
|
33 | }
|
34 |
|
35 |
|
36 |
|
37 | var usage = [
|
38 | 'Usage: ' + pkg.name + ' [OPTIONS] [<input file> [<output file>]]',
|
39 | '',
|
40 | ' -d, --dynamic-typing',
|
41 | ' Convert booleans and numeric to their type instead of strings.',
|
42 | '',
|
43 | ' -s <separator>, --separator=<separator>',
|
44 | ' Field separator to use (default to comma “,”).',
|
45 | '',
|
46 | ' -t, --tsv',
|
47 | ' Use tab as separator, overrides separator flag.',
|
48 | '',
|
49 | ' <input file>',
|
50 | ' CSV file to read data from.',
|
51 | ' If unspecified or a dash (“-”), use the standard input.',
|
52 | '',
|
53 | ' <output file>',
|
54 | ' JSON file to write data to.',
|
55 | ' If unspecified or a dash (“-”), use the standard output.',
|
56 | '',
|
57 | pkg.name + ' v' + pkg.version
|
58 | ].join('\n')
|
59 |
|
60 | function main (args) {
|
61 | args = minimist(args, {
|
62 | boolean: ['dynamic-typing', 'help', 'tsv'],
|
63 | string: 'separator',
|
64 |
|
65 | alias: {
|
66 | help: 'h',
|
67 | d: 'dynamic-typing',
|
68 | separator: 's',
|
69 | tsv: 't'
|
70 | }
|
71 | })
|
72 |
|
73 | if (args.help) {
|
74 | return usage
|
75 | }
|
76 |
|
77 | return eventToPromise(pump([
|
78 | createInputStream(args._[0]),
|
79 | csv2json({
|
80 | dynamicTyping: args['dynamic-typing'],
|
81 | separator: args.tsv ? '\t' : args.separator
|
82 | }),
|
83 | createOutputStream(args._[1])
|
84 | ]), 'finish')
|
85 | }
|
86 | exports = module.exports = main
|
87 |
|
88 |
|
89 |
|
90 | if (!module.parent) {
|
91 | require('exec-promise')(exports)
|
92 | }
|