mdview.js
1.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
"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;