cli.js 797 B

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