cli.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. #!/usr/bin/env node
  2. // cli.js
  3. // JSON5 command-line interface.
  4. //
  5. // This is pretty minimal for now; just supports compiling files via `-c`.
  6. // TODO More useful functionality, like output path, watch, etc.?
  7. var FS = require('fs');
  8. var JSON5 = require('./json5');
  9. var Path = require('path');
  10. var USAGE = [
  11. 'Usage: json5 -c path/to/file.json5 ...',
  12. 'Compiles JSON5 files into sibling JSON files with the same basenames.',
  13. ].join('\n');
  14. // if valid, args look like [node, json5, -c, file1, file2, ...]
  15. var args = process.argv;
  16. if (args.length < 4 || args[2] !== '-c') {
  17. console.error(USAGE);
  18. process.exit(1);
  19. }
  20. var cwd = process.cwd();
  21. var files = args.slice(3);
  22. // iterate over each file and convert JSON5 files to JSON:
  23. files.forEach(function (file) {
  24. var path = Path.resolve(cwd, file);
  25. var basename = Path.basename(path, '.json5');
  26. var dirname = Path.dirname(path);
  27. var json5 = FS.readFileSync(path, 'utf8');
  28. var obj = JSON5.parse(json5);
  29. var json = JSON.stringify(obj, null, 4); // 4 spaces; TODO configurable?
  30. path = Path.join(dirname, basename + '.json');
  31. FS.writeFileSync(path, json, 'utf8');
  32. });