1 | #!/usr/bin/env node
|
2 |
|
3 | const fs = require('fs')
|
4 | const path = require('path')
|
5 | const minimist = require('minimist')
|
6 | const pkg = require('../package.json')
|
7 | const JSON5 = require('./')
|
8 |
|
9 | const argv = minimist(process.argv.slice(2), {
|
10 | alias: {
|
11 | 'convert': 'c',
|
12 | 'space': 's',
|
13 | 'validate': 'v',
|
14 | 'out-file': 'o',
|
15 | 'version': 'V',
|
16 | 'help': 'h',
|
17 | },
|
18 | boolean: [
|
19 | 'convert',
|
20 | 'validate',
|
21 | 'version',
|
22 | 'help',
|
23 | ],
|
24 | string: [
|
25 | 'space',
|
26 | 'out-file',
|
27 | ],
|
28 | })
|
29 |
|
30 | if (argv.version) {
|
31 | version()
|
32 | } else if (argv.help) {
|
33 | usage()
|
34 | } else {
|
35 | const inFilename = argv._[0]
|
36 |
|
37 | let readStream
|
38 | if (inFilename) {
|
39 | readStream = fs.createReadStream(inFilename)
|
40 | } else {
|
41 | readStream = process.stdin
|
42 | }
|
43 |
|
44 | let json5 = ''
|
45 | readStream.on('data', data => {
|
46 | json5 += data
|
47 | })
|
48 |
|
49 | readStream.on('end', () => {
|
50 | let space
|
51 | if (argv.space === 't' || argv.space === 'tab') {
|
52 | space = '\t'
|
53 | } else {
|
54 | space = Number(argv.space)
|
55 | }
|
56 |
|
57 | let value
|
58 | try {
|
59 | value = JSON5.parse(json5)
|
60 | if (!argv.validate) {
|
61 | const json = JSON.stringify(value, null, space)
|
62 |
|
63 | let writeStream
|
64 |
|
65 |
|
66 |
|
67 |
|
68 | if (argv.convert && inFilename && !argv.o) {
|
69 | const parsedFilename = path.parse(inFilename)
|
70 | const outFilename = path.format(
|
71 | Object.assign(
|
72 | parsedFilename,
|
73 | {base: path.basename(parsedFilename.base, parsedFilename.ext) + '.json'}
|
74 | )
|
75 | )
|
76 |
|
77 | writeStream = fs.createWriteStream(outFilename)
|
78 | } else if (argv.o) {
|
79 | writeStream = fs.createWriteStream(argv.o)
|
80 | } else {
|
81 | writeStream = process.stdout
|
82 | }
|
83 |
|
84 | writeStream.write(json)
|
85 | }
|
86 | } catch (err) {
|
87 | console.error(err.message)
|
88 | process.exit(1)
|
89 | }
|
90 | })
|
91 | }
|
92 |
|
93 | function version () {
|
94 | console.log(pkg.version)
|
95 | }
|
96 |
|
97 | function usage () {
|
98 | console.log(
|
99 | `
|
100 | Usage: json5 [options] <file>
|
101 |
|
102 | If <file> is not provided, then STDIN is used.
|
103 |
|
104 | Options:
|
105 |
|
106 | -s, --space The number of spaces to indent or 't' for tabs
|
107 | -o, --out-file [file] Output to the specified file, otherwise STDOUT
|
108 | -v, --validate Validate JSON5 but do not output JSON
|
109 | -V, --version Output the version number
|
110 | -h, --help Output usage information`
|
111 | )
|
112 | }
|