Skip to content

Node.js Markdown 转 HTML

将 Markdown 文件转换成 HTML 页面,使用三个库配合完成。

工具链

作用
EJSJavaScript 模板引擎,将数据渲染为 HTML
MarkedMarkdown 解析器,将 .md 语法转为 HTML 标记
BrowserSync实时预览,自动刷新浏览器

EJS 模板语法速查

标签用途示例
<% code %>执行 JS,无输出<% if (x) { %>
<%= value %>输出(会转义 HTML 字符)<%= title %>
<%- value %>输出原始 HTML(不转义)<%- content %>
<%- include('file') %>引入其他模板组件复用
ejs
<!-- template.ejs -->
<!DOCTYPE html>
<html>
<body>
  <h1><%= title %></h1>
  <%- content %>     <!-- 这里放编译后的 HTML -->
</body>
</html>

核心流程

1. 用 Marked 转换 MD → HTML

js
const marked = require('marked')
const mdContent = fs.readFileSync('./readme.md', 'utf-8')
const htmlContent = marked.parse(mdContent)

2. 用 EJS 渲染模板

js
const ejs = require('ejs')
ejs.renderFile('./template.ejs', {
  title: '文档标题',
  content: htmlContent  // marked 输出的 HTML
}, (err, str) => {
  fs.writeFileSync('./index.html', str)
})

3. 用 BrowserSync 预览

js
const browserSync = require('browser-sync')
const browser = browserSync.create()
browser.init({
  server: { baseDir: './', index: 'index.html' }
})
// 文件变化自动刷新浏览器

流程总结

readme.md  →  marked.parse()  →  HTML片段

template.ejs + HTML片段  →  ejs.renderFile()  →  index.html

                              browserSync.init()  →  浏览器实时预览