標籤:小程式 family watch require utf-8 else 方法 ace 版本
1.版本一
- 1.1`npm install marked --save` 安裝markdwon轉html的包.
- 1.2 使用watchFile監視 markdown檔案
/** * Created by liyinghao on 2016/11/8. */const fs = require(‘fs‘)const marked = require(‘marked‘)//1.即時監視note.md檔案的變化fs.watchFile(‘./note.md‘,(curr,prev)=>{ //2.讀取note.md檔案的內容 fs.readFile(‘./note.md‘,‘utf-8‘,(err,data)=>{ if(err){ throw err }else{ //3.使用marked方法,將md格式的檔案轉化為html格式 let htmlStr = marked(data.toString()); //4.將轉化的html格式的字串,寫入到新的檔案中 fs.writeFile(‘./new.html‘,htmlStr,err=>{ if(err){ throw err }else{ console.log("success"); } }) } })})
2.版本二:使用一個事先準備好的html模板,包含一些樣式
/** * Created by liyinghao on 2016/11/8. */const fs = require(‘fs‘)const marked = require(‘marked‘)fs.watchFile(‘./note.md‘,(curr,prev)=>{ //讀取準備好的html模板檔案 fs.readFile(‘./template.html‘,‘utf8‘,(err,template)=>{ if(err){ throw err }else{ fs.readFile(‘./note.md‘,‘utf8‘,(err,markContent)=>{ if(err){ throw err }else{ //轉化好的html字串 let htmlStr = marked(markContent.toString()); //將html模板檔案中的‘@markdown‘ 替換為 html字串 template.replace(‘@markdown‘, htmlStr) //將新產生的字串template重新寫入到檔案中 fs.writeFile(‘./template.html‘,template,err=>{ if(err){ throw err }else{ console.log("success"); } }) } }) } })});
基於nodejs的一個即時markdown轉html工具小程式