view-markdown.js 1.74 KB
/**
 * view-markdown
 * Created by lintry on 2018/1/9.
 */

const path = require('path');


class ViewMarkdown {
    constructor (doc_path, options) {
        this.options = options || {};
        if (!doc_path) {
            throw new Error('document path for markdown not found')
        }

        this.doc_path = doc_path;
        this.mdviewer = new (require('./mdviewer'))({parseTokens: true, toc: this.options.toc});
    }

    /**
     * 渲染文件
     * @param filename 文件名,绝对路径
     * @param theme 主题
     * @return {string}
     */
    render (filename, theme) {
        const options = this.options;
        //默认md
        if (!filename || filename.match(/.+\/$/)) {
            filename = (filename || '') + (options.default_md || 'readme.md')
        }
        let file = path.resolve(this.doc_path, filename);
        if (!path.parse(file).ext) {
            //追加后缀
            file += '.md'
        }
        let result = this.mdviewer.renderFile(file);
        let tittle = result.tokens && result.tokens[1] && result.tokens[1].content || filename;
        theme = theme || options.theme;
        let content = result.status === 404 ? this.mdviewer.render(`
# 404
> **${filename}不存在**
`)
            : result.html;
        return `
    <!DOCTYPE html>
    <html>
        <head>
            <meta charset=utf-8>
            <title>${tittle}</title>
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <link rel="stylesheet" href="/markdown.css">
            <link rel="stylesheet" href="/${theme}/${theme}.css">
        </head>
        <body>
        <div class='markdown ${theme}'>
        ${content}
        </div>
        </body
    </html>
`;
    }
}

module.exports = ViewMarkdown;