LoginSignup
5
4

More than 5 years have passed since last update.

NodeでMarkdownをHTML化する

Posted at

概要

タイトル通りの小ネタです。

  • MD→HTML変換は markdown というライブラリで簡単にできます。
  • 逆方向は html-to-markdown というライブラリを使うとできますが出力結果はいまいちでした。理由は、MDファイル内にHTMLが直接埋め込めるためです。

MD2HTMLのコード

md-to-html.js
const html = require('html')
const markdown = require('markdown')
const fs = require('fs')

main()

function main() {
  if(process.argv.length !== 3) {
    console.log("Usage: md-to-html.bat <markdown file>")
    process.exit()
    return
  }

  const mdFile = process.argv[2]
  console.log("Input File:" + mdFile)
  const contents = fs.readFileSync(mdFile, {encoding:'utf-8'})
  const output = html.prettyPrint(markdown.markdown.toHTML(contents))
  const outFile = mdFile + ".html"
  console.log("Outputing File: " + outFile)
  fs.writeFileSync(outFile, output, "utf-8")
  console.log("Completed.")
}

以下のバッチを作ってドラッグ&ドロップすると変換されます。

md-to-html.bat
node ./md-to-html.js %1

逆方向(HTML2MD)

html-to-md.js
const converter = require('html-to-markdown')
const fs = require('fs')

main()

function main() {
  if(process.argv.length !== 3) {
    console.log("Usage: html-to-md.bat <html file>")
    process.exit()
    return
  }

  const htmlFile = process.argv[2]
  console.log("Input File:" + htmlFile)
  const contents = fs.readFileSync(htmlFile, {encoding:'utf-8'})
  const output = converter.convert(contents);
  const outFile = htmlFile + ".md"
  console.log("Outputing File: " + outFile)
  fs.writeFileSync(outFile, output, "utf-8")
  console.log("Completed.")
}
5
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4