markdown-it.mjs 2.1 KB

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