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文件名称;就可以动态监听修改
相关文章推荐
- node.js 监听文件变化并打印
- 第1章-安装Node.js及相关要点-1.10.监听文件变化
- python实现将html表格转换成CSV文件的方法
- Linux下批量将md文件批量转换为html文件
- 在windows 下将 chm 格式的文件 转换成 html 的文件
- ubuntu下用java代码调用命令将java格式文件转换为html格式文件
- NodeJS express访问html,css,JS等静态资源文件
- Word/Excel/PDF文件转换成HTML整理
- Flume监听文件夹中的文件变化,并把文件下沉到hdfs
- pdf文件转换成html格式的实用方法
- 文件如何转换成pdf或html格式
- C# 使用 wkhtmltopdf 把HTML文本或文件转换为PDF
- htmldoc能够将html转换成PDF文件
- Android Service监听SD卡某目录变化,并获取文件Path
- ABAP将内表数据转换为HTML格式的文件
- md文件转为html的步骤
- gulp监听文件变化,并拷贝到指定目录
- itext xmlworker转换html生成pdf文件
- 将 HTML 文件转换成 XML
- HTML5外包团队——技术分享:HTML5判断设备在线离线及监听网络状态变化例子