cli.js 2.8 KB

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