Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

108 строки
2.3KB

  1. #!/usr/bin/env node
  2. var fs = require('fs');
  3. var Mustache = require('..');
  4. var pkg = require('../package');
  5. var viewArg = process.argv[2];
  6. var templateArg = process.argv[3];
  7. if (hasVersionArg()) {
  8. return console.log(pkg.version);
  9. }
  10. if (!templateArg || !viewArg) {
  11. console.error('Syntax: mustache <view> <template>');
  12. process.exit(1);
  13. }
  14. run(readView, readTemplate, render, toStdout);
  15. /**
  16. * Runs a list of functions as a waterfall.
  17. * Functions are runned one after the other in order, providing each
  18. * function the returned values of all the previously invoked functions.
  19. * Each function is expected to exit the process if an error occurs.
  20. */
  21. function run(/*args*/) {
  22. var values = [];
  23. var fns = Array.prototype.slice.call(arguments);
  24. function invokeNextFn(val) {
  25. values.unshift(val);
  26. if (fns.length == 0) return;
  27. invoke(fns.shift());
  28. }
  29. function invoke(fn) {
  30. fn.apply(null, [invokeNextFn].concat(values));
  31. }
  32. invoke(fns.shift());
  33. }
  34. function readView(cb) {
  35. var view = isStdin(viewArg) ? process.openStdin() : fs.createReadStream(viewArg);
  36. streamToStr(view, function(str) {
  37. cb(parseView(str));
  38. });
  39. }
  40. function parseView(str) {
  41. try {
  42. return JSON.parse(str);
  43. } catch (ex) {
  44. console.error(
  45. 'Shooot, could not parse view as JSON.\n'+
  46. 'Tips: functions are not valid JSON and keys / values must be surround with double quotes.\n\n'+
  47. ex.stack);
  48. process.exit(1);
  49. }
  50. }
  51. function readTemplate(cb) {
  52. var template = fs.createReadStream(templateArg);
  53. streamToStr(template, cb);
  54. }
  55. function render(cb, templateStr, jsonView) {
  56. cb(Mustache.render(templateStr, jsonView));
  57. }
  58. function toStdout(cb, str) {
  59. cb(process.stdout.write(str));
  60. }
  61. function streamToStr(stream, cb) {
  62. var data = '';
  63. stream.on('data', function(chunk) {
  64. data += chunk;
  65. }).once('end', function() {
  66. cb(data.toString());
  67. }).on('error', function(err) {
  68. if (wasNotFound(err)) {
  69. console.error('Could not find file:', err.path);
  70. } else {
  71. console.error('Error while reading file:', err.message);
  72. }
  73. process.exit(1);
  74. });
  75. }
  76. function isStdin(viewArg) {
  77. return viewArg === '-';
  78. }
  79. function wasNotFound(err) {
  80. return err.code && err.code === 'ENOENT';
  81. }
  82. function hasVersionArg() {
  83. return ['--version', '-v'].some(function(opt) {
  84. return process.argv.indexOf(opt) > -1;
  85. });
  86. }