基於nodejs的一個實時markdown轉html工具小程序


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");
                        }
                    })
                }
            })
        }
    })
});

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM