想將md轉(zhuǎn)義為html,本質(zhì)上就是利用正則將md語句轉(zhuǎn)義為html語句,這里我們利用現(xiàn)有的轉(zhuǎn)義庫 marked
首先
新建一個空的倉庫 mdToHtml
mkdir mdToHtml
cd mdToHtml/
npm init
下載marked, 新建文件
npm i marked
touch index.js
touch test.md
test.md
### 標(biāo)題
index.js
// 首先引入我們需要用到的模塊
const fs = require("fs")
const path = require("path")
const marked = require("marked")
// md文件路徑
const filepath = path.join(__dirname, 'test.md')
// fs 讀取文件內(nèi)容
fs.readFile(filepath, "utf8", (err, data) => {
if (err) {
console.log(err);
return;
}
let html = marked(data);
console.log(data, html)
})
打開控制臺輸入 node index.js

image.png
現(xiàn)在已經(jīng)將md語句轉(zhuǎn)換為html標(biāo)簽了,接下來,我們那用模版字符串,生成一個完整的html頁面
首先下載ejs
創(chuàng)建模版字符串
const ejs = require('ejs')
const template = `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Md to Html</title>
</head>
<body>
<%- html %>
<%#輸出非轉(zhuǎn)義的數(shù)據(jù)html到模板%>
</body>
</html>`
let pageHtml = ejs.render(template,{html})
console.log(data, html,pageHtml)
內(nèi)容已經(jīng)產(chǎn)生了,結(jié)下來就需要生成文件,并將內(nèi)容寫入文件了,還是利用fs模塊
// fs.mkdir 創(chuàng)建目錄
fs.mkdir('Public', function (error) {
if (error) {
console.log(error);
return false;
}
console.log('創(chuàng)建目錄成功');
})
//fs.writeFile 寫入文件(會覆蓋之前的內(nèi)容)(文件不存在就創(chuàng)建) utf8參數(shù)可以省略
fs.writeFile('Public/index.html', pageHtml, 'utf8', function (error) {
if (error) {
console.log(error);
return false;
}
console.log('寫入成功');
})
運行腳本

image.png
生成如下目錄
.
├── Public
│ └── index.html
├── README.md
├── index.js
├── node_modules
│ ├── ejs
│ └── marked
├── package-lock.json
├── package.json
└── test.md
查看Public/index.html文件

image.png
瀏覽器中查看

image.png
更方便一點,我們可以用fs的監(jiān)聽md文件的變化,自動執(zhí)行腳本
fs.watch(filepath,( function () {
var count = 0;
return function(){
count++;
console.log("文件" + filepath + " 內(nèi)容剛剛改變。。第" + count + "次" );
// todo
})
fs.watch的最大缺點就是不支持子文件夾的偵聽,并且在很多情況下會偵聽到兩次事件(很多編輯器在保存的時侯是先把原文件清空,再進(jìn)行保存,因此會觸發(fā)兩次文件夾改變事件)。因此需要一些開源的模塊來監(jiān)聽文件夾目錄的改變。感興趣的同學(xué)可以自己找一下解決方案。
完整代碼