cli.js 895 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. #!/usr/bin/env node
  2. const fs = require('fs')
  3. const path = require('path')
  4. const readline = require('readline')
  5. const flat = require('./index')
  6. const filepath = process.argv.slice(2)[0]
  7. if (filepath) {
  8. // Read from file
  9. const file = path.resolve(process.cwd(), filepath)
  10. fs.accessSync(file, fs.constants.R_OK) // allow to throw if not readable
  11. out(require(file))
  12. } else if (process.stdin.isTTY) {
  13. usage(0)
  14. } else {
  15. // Read from newline-delimited STDIN
  16. const lines = []
  17. readline.createInterface({
  18. input: process.stdin,
  19. output: process.stdout,
  20. terminal: false
  21. })
  22. .on('line', line => lines.push(line))
  23. .on('close', () => out(JSON.parse(lines.join('\n'))))
  24. }
  25. function out (data) {
  26. process.stdout.write(JSON.stringify(flat(data), null, 2))
  27. }
  28. function usage (code) {
  29. console.log(`
  30. Usage:
  31. flat foo.json
  32. cat foo.json | flat
  33. `)
  34. process.exit(code || 0)
  35. }