写好的Markdown怎么生成HTML

html-css07

写好的Markdown怎么生成HTML,第1张

在简书里写文章时,有个预览模式,左边用markdown语法写,右边能实时预览到最终效果,今天看到一个实现类似功能的demo,所以准备写下来留个笔记

利用文件监视实现自动将markdown文件转换为html文档

实现思路:

利用 fs模块的文件监视功能fs.watch(filename,listener)监视指定markdown文件. (可以理解为发布订阅模式,每当文件发生变化,发布消息,订阅者收到消息)

当文件发生变化后,借助 marked包提供的markdown to html 功能将改变后的md文件转换为html格式。

将得到的html以及读入的css文件替换到模板,得到最终要渲染的html.

最后利用BrowserSync模块实现浏览器自动刷新,即每当改变markdown文件,浏览器中会自动刷新显示

代码不多:

const fs = require('fs')

const path = require('path')

const marked = require('marked')

const browserSync = require('browser-sync')//接收需要转换的文件路径

const target = path.join(__dirname, process.argv[2] || 'README.md')//最终生成的html文件的位置

const filename = target.replace(path.extname(target), '.html')//获取html文件名

const indexpath = path.basename(filename)//通过browser-sync创建一个文件服务器

browserSync({

    notify: false,

    server: path.dirname(target),//网站根目录

    index: indexpath//默认文档

})//监视文件变化,可以理解为当文件发生变化(需要保存才能触发文件变化),interval时间间隔后调用回调函数

fs.watchFile(target, { interval: 200 }, (cur, prev) => {

    // console.log(`current:${cur.size} previous:${prev.size}`)

    //判断文件的最后修改时间是否改变,减少不必要的转换

    if (cur.mtime === prev.mtime) {

        return false

    }

    fs.readFile(target, 'utf8', (err, content) => {

        if (err) {

            throw err

        }

        let html = marked(content)

        // console.log(html)

        fs.readFile(path.join(__dirname, 'github.css'), 'utf8', (err, css) => {

            html = template.replace('{{{content}}}', html).replace('{{{styles}}}', css)

            // console.log(html)

            fs.writeFile(filename, html, (err) => {

                if (err) {

                    throw err

                }

                browserSync.reload(indexpath)

                console.log('updated@' + new Date())

            })

        })

    })

})

const template = `<!DOCTYPE html><html lang="en"><head>

    <meta charset="UTF-8">

    <title>Markdown to Html</title>

    <style>{{{styles}}}</style></head><body>

    <div class='vs'>

    {{{content}}}

    </div>

</body>

</html>`

运行后每当改变markdown文件(ctrl+s),页面会自动刷新,和简书的预览效果基本差不多。

源码:https://github.com/Hfimy/markdownTohtml

参考:http://www.jianshu.com/p/f697a5471cc3

markdown文件一般可以用记事本等文本编辑器打开,但是看不到排版效果,只有生成html或者pdf之后才有效果。那么markdown文件怎么转换成html或者pdf文件呢?来看看小编的介绍吧。

工具/原料

markdownPad软件

markdown文件

方法/步骤

首先我们需要安装markdownPad软件,这是专门编辑和生成转换markdown文件为html或者pdf文件的软件,下载安装激活教程如下。

0markdownPad免费用注册码/秘钥激活

markdown文件怎么转换成html或者pdf文件

然后我们把markdown文件用markdownPad软件打开。左边是源码右边是效果。

markdown文件怎么转换成html或者pdf文件

然后我们点击菜单栏的“文件”,之后是“导出”,再选择导出的格式,可以看到有html和pdf两项。

markdown文件怎么转换成html或者pdf文件

保存为html文件后,markdown文件可以直接用浏览器打开。

markdown文件怎么转换成html或者pdf文件

5

保存为pdf文件后,markdown文件可以直接用pdf阅读器打开。

markdown文件怎么转换成html或者pdf文件

END

注意事项

markdown文件怎么转换成html或者pdf文件