码迷,mamicode.com
首页 > Web开发 > 详细

基于nodejs的一个实时markdown转html工具小程序

时间:2016-11-08 22:31:03      阅读:257      评论:0      收藏:0      [点我收藏+]

标签:小程序   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工具小程序

标签:小程序   family   watch   require   utf-8   else   方法   ace   版本   

原文地址:http://www.cnblogs.com/itlyh/p/6044832.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!