markdown-it 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. #!/usr/bin/env node
  2. /*eslint no-console:0*/
  3. 'use strict';
  4. var fs = require('fs');
  5. var argparse = require('argparse');
  6. ////////////////////////////////////////////////////////////////////////////////
  7. var cli = new argparse.ArgumentParser({
  8. prog: 'markdown-it',
  9. version: require('../package.json').version,
  10. addHelp: true
  11. });
  12. cli.addArgument([ '--no-html' ], {
  13. help: 'Disable embedded HTML',
  14. action: 'storeTrue'
  15. });
  16. cli.addArgument([ '-l', '--linkify' ], {
  17. help: 'Autolink text',
  18. action: 'storeTrue'
  19. });
  20. cli.addArgument([ '-t', '--typographer' ], {
  21. help: 'Enable smartquotes and other typographic replacements',
  22. action: 'storeTrue'
  23. });
  24. cli.addArgument([ '--trace' ], {
  25. help: 'Show stack trace on error',
  26. action: 'storeTrue'
  27. });
  28. cli.addArgument([ 'file' ], {
  29. help: 'File to read',
  30. nargs: '?',
  31. defaultValue: '-'
  32. });
  33. cli.addArgument([ '-o', '--output' ], {
  34. help: 'File to write',
  35. defaultValue: '-'
  36. });
  37. var options = cli.parseArgs();
  38. function readFile(filename, encoding, callback) {
  39. if (options.file === '-') {
  40. // read from stdin
  41. var chunks = [];
  42. process.stdin.on('data', function (chunk) { chunks.push(chunk); });
  43. process.stdin.on('end', function () {
  44. return callback(null, Buffer.concat(chunks).toString(encoding));
  45. });
  46. } else {
  47. fs.readFile(filename, encoding, callback);
  48. }
  49. }
  50. ////////////////////////////////////////////////////////////////////////////////
  51. readFile(options.file, 'utf8', function (err, input) {
  52. var output, md;
  53. if (err) {
  54. if (err.code === 'ENOENT') {
  55. console.error('File not found: ' + options.file);
  56. process.exit(2);
  57. }
  58. console.error(
  59. options.trace && err.stack ||
  60. err.message ||
  61. String(err));
  62. process.exit(1);
  63. }
  64. md = require('..')({
  65. html: !options['no-html'],
  66. xhtmlOut: false,
  67. typographer: options.typographer,
  68. linkify: options.linkify
  69. });
  70. try {
  71. output = md.render(input);
  72. } catch (e) {
  73. console.error(
  74. options.trace && e.stack ||
  75. e.message ||
  76. String(e));
  77. process.exit(1);
  78. }
  79. if (options.output === '-') {
  80. // write to stdout
  81. process.stdout.write(output);
  82. } else {
  83. fs.writeFileSync(options.output, output);
  84. }
  85. });