markdown-it.js 2.2 KB

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