json2yaml.js 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. /**
  2. * yaml2json cli program
  3. */
  4. var YAML = require('../lib/Yaml.js');
  5. var ArgumentParser = require('argparse').ArgumentParser;
  6. var cli = new ArgumentParser({
  7. prog: "json2yaml",
  8. version: require('../package.json').version,
  9. addHelp: true
  10. });
  11. cli.addArgument(
  12. ['-d', '--depth'],
  13. {
  14. action: 'store',
  15. type: 'int',
  16. help: 'Set minimum level of depth before generating inline YAML (default: 2).'
  17. }
  18. );
  19. cli.addArgument(
  20. ['-i', '--indentation'],
  21. {
  22. action: 'store',
  23. type: 'int',
  24. help: 'Number of space characters used to indent code (default: 2).',
  25. }
  26. );
  27. cli.addArgument(
  28. ['-s', '--save'],
  29. {
  30. help: 'Save output inside YML file(s) with the same name.',
  31. action: 'storeTrue'
  32. }
  33. );
  34. cli.addArgument(
  35. ['-r', '--recursive'],
  36. {
  37. help: 'If the input is a directory, also find JSON files in sub-directories recursively.',
  38. action: 'storeTrue'
  39. }
  40. );
  41. cli.addArgument(
  42. ['-w', '--watch'],
  43. {
  44. help: 'Watch for changes.',
  45. action: 'storeTrue'
  46. }
  47. );
  48. cli.addArgument(['input'], {
  49. help: 'JSON file or directory containing JSON files or - to read JSON from stdin.'
  50. });
  51. try {
  52. var options = cli.parseArgs();
  53. var path = require('path');
  54. var fs = require('fs');
  55. var glob = require('glob');
  56. var rootPath = process.cwd();
  57. var parsePath = function(input) {
  58. if (input == '-') return '-';
  59. var output;
  60. if (!(input != null)) {
  61. return rootPath;
  62. }
  63. output = path.normalize(input);
  64. if (output.length === 0) {
  65. return rootPath;
  66. }
  67. if (output.charAt(0) !== '/') {
  68. output = path.normalize(rootPath + '/./' + output);
  69. }
  70. if (output.length > 1 && output.charAt(output.length - 1) === '/') {
  71. return output.substr(0, output.length - 1);
  72. }
  73. return output;
  74. };
  75. // Find files
  76. var findFiles = function(input) {
  77. if (input != '-' && input != null) {
  78. var isDirectory = fs.statSync(input).isDirectory();
  79. var files = [];
  80. if (!isDirectory) {
  81. files.push(input);
  82. }
  83. else {
  84. if (options.recursive) {
  85. files = files.concat(glob.sync(input+'/**/*.json'));
  86. }
  87. else {
  88. files = files.concat(glob.sync(input+'/*.json'));
  89. }
  90. }
  91. return files;
  92. }
  93. return null;
  94. };
  95. // Convert to JSON
  96. var convertToYAML = function(input, inline, save, spaces, str) {
  97. var yaml;
  98. if (inline == null) inline = 2;
  99. if (spaces == null) spaces = 2;
  100. if (str == null) {
  101. str = ''+fs.readFileSync(input);
  102. }
  103. yaml = YAML.dump(JSON.parse(str), inline, spaces);
  104. if (!save || input == null) {
  105. // Ouput result
  106. process.stdout.write(yaml);
  107. }
  108. else {
  109. var output;
  110. if (input.substring(input.length-5) == '.json') {
  111. output = input.substr(0, input.length-5) + '.yaml';
  112. }
  113. else {
  114. output = input + '.yaml';
  115. }
  116. // Write file
  117. var file = fs.openSync(output, 'w+');
  118. fs.writeSync(file, yaml);
  119. fs.closeSync(file);
  120. process.stdout.write("saved "+output+"\n");
  121. }
  122. };
  123. var input = parsePath(options.input);
  124. var mtimes = [];
  125. var runCommand = function() {
  126. try {
  127. var files = findFiles(input);
  128. if (files != null) {
  129. var len = files.length;
  130. for (var i = 0; i < len; i++) {
  131. var file = files[i];
  132. var stat = fs.statSync(file);
  133. var time = stat.mtime.getTime();
  134. if (!stat.isDirectory()) {
  135. if (!mtimes[file] || mtimes[file] < time) {
  136. mtimes[file] = time;
  137. convertToYAML(file, options.depth, options.save, options.indentation);
  138. }
  139. }
  140. }
  141. } else {
  142. // Read from STDIN
  143. var stdin = process.openStdin();
  144. var data = "";
  145. stdin.on('data', function(chunk) {
  146. data += chunk;
  147. });
  148. stdin.on('end', function() {
  149. convertToYAML(null, options.depth, options.save, options.indentation, data);
  150. });
  151. }
  152. } catch (e) {
  153. process.stderr.write((e.message ? e.message : e)+"\n");
  154. }
  155. };
  156. if (!options.watch) {
  157. runCommand();
  158. } else {
  159. runCommand();
  160. setInterval(runCommand, 1000);
  161. }
  162. } catch (e) {
  163. process.stderr.write((e.message ? e.message : e)+"\n");
  164. }