-
Notifications
You must be signed in to change notification settings - Fork 0
/
cli.js
executable file
·42 lines (35 loc) · 895 Bytes
/
cli.js
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
#!/usr/bin/env node
const fs = require('fs')
const path = require('path')
const readline = require('readline')
const flat = require('./index')
const filepath = process.argv.slice(2)[0]
if (filepath) {
// Read from file
const file = path.resolve(process.cwd(), filepath)
fs.accessSync(file, fs.constants.R_OK) // allow to throw if not readable
out(require(file))
} else if (process.stdin.isTTY) {
usage(0)
} else {
// Read from newline-delimited STDIN
const lines = []
readline.createInterface({
input: process.stdin,
output: process.stdout,
terminal: false
})
.on('line', line => lines.push(line))
.on('close', () => out(JSON.parse(lines.join('\n'))))
}
function out (data) {
process.stdout.write(JSON.stringify(flat(data), null, 2))
}
function usage (code) {
console.log(`
Usage:
flat foo.json
cat foo.json | flat
`)
process.exit(code || 0)
}