mdview.js 1.26 KB
"use strict";
const fs = require('fs');

/**
 * 渲染md文件,输出html
 * @param opts 选项
 * @return {MarkdownIt}
 * @constructor
 *
 * opts:
 * toc: true/false 是否显示[TOC]
 * parseTokens: true/false 是否同时解析md输出结果tokens
 */
function MarkdownIt (opts) {
    if (!(this instanceof MarkdownIt)) {
        return new MarkdownIt(opts);
    }

    opts = opts || {};

    const md = require('markdown-it')(opts.options);
    if (opts.toc) {
        md.use(require('markdown-it-github-toc').default, {
            anchorLinkSymbol: ''
        })
    }
    this.renderFile = function (filename) {
        if (!filename) {
            throw new Error('filename can not be null!')
        }

        let result = {}, content;
        try {
            content = fs.readFileSync(filename).toString();
            result.html = md.render(content);
        } catch (e) {
            console.error('convert md to html error', e);
            result.html = md.render(`
# 404
*文件找不到!*
`)
        }

        try {
            if (opts.parseTokens) {
                result.tokens = md.parse(content, {});
            }
        } catch (e) {
            console.error('parse md error', e)
        }

        return result;
    }
}

module.exports = MarkdownIt;