UNPKG

2.3 kBJavaScriptView Raw
1#!/usr/bin/env node
2
3'use strict'
4
5var createReadStream = require('fs').createReadStream
6var createWriteStream = require('fs').createWriteStream
7var PassThrough = require('stream').PassThrough
8
9var eventToPromise = require('promise-toolbox/fromEvent')
10var minimist = require('minimist')
11var pump = require('pump')
12
13var csv2json = require('./')
14var pkg = require('./package.json')
15
16// ===================================================================
17
18function createInputStream (path) {
19 return path === undefined || path === '-'
20 ? process.stdin
21 : createReadStream(path)
22}
23
24function createOutputStream (path) {
25 if (path !== undefined && path !== '-') {
26 return createWriteStream(path)
27 }
28
29 // introduce a through stream because stdout is not a normal stream!
30 var stream = new PassThrough()
31 stream.pipe(process.stdout)
32 return stream
33}
34
35// ===================================================================
36
37var 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
60function 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}
86exports = module.exports = main
87
88// ===================================================================
89
90if (!module.parent) {
91 require('exec-promise')(exports)
92}