您的位置:首页 > Web前端 > Node.js

node 监听md文件变化并转换成html

2017-12-07 11:22 197 查看

监听md文件是否变化,变化了就读取md文件,并使用库转换成HTML;

监听: fs.watchFile(filename, (cur ,pre) =< {})

读取: fs.readFile;

监听是否变化: cur.mtime / pre.mtime; //cur 和 pre 都是fs.Stats的实例;都有stats属性;

转换: 使用marked库,安装 install marked –save

转换成功,拼合html代码

写入html文件;

添加样式;

自动刷新

const fs = require("fs");
const path = require("path");
const marked = require("marked");

const filepath= path.join(__dirname, process.argv[2]);

const template = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div>{{{content}}}</div>
</body>
</html>`

fs.watchFile(filePath, (cur, pre) => {//options: 监听失效等
if(cur.mtime !== pre.mtime) {

//读取文件并转换写入
fs.readFile(filePath, "utf8", (err,data) => {
if(err) {console.log(err);return;}
let html =  marked(data);

//因为md文件转换成HTML 没有body等标签,需替换添加
template = html.replace("{{{content}}}", html);

//写入html
fs.writeFile(path.join(__dirname, "watch.html"), template, "utf8");
})
}
})


还可以下载md样式表文件,替换添加到页面中;最好使用style标签的方式添加,而不是使用link,因为link方式文件路径动态变化会出错;

自动刷新

使用broswer-sync库

1.  install browser-sync --save
2.  watch.js中开始处创建browser 服务
var browserSync = require("browser-sync");
browserSync({server: __dirname});

3.写入文件完成后执行browser  relaod命令;


完成后修改md文件,浏览器自动打开localhost页面;输入html文件名称;就可以动态监听修改
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: