mdviewer.js
1.61 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
"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);
result.status = 200;
} catch (e) {
// console.error('convert md to html error', e);
result.status = 404;
}
try {
if (opts.parseTokens) {
result.tokens = md.parse(content, {});
}
} catch (e) {
// console.warn('parse md error', e)
}
return result;
};
/**
* 返回渲染文本
* @param src
* @param env
* @return {*}
*/
this.render = function (src, env) {
return md.render(src, env)
};
/**
* 返回解析文本
* @param src
* @param env
* @return {*}
*/
this.parse = function (src, env) {
return md.parse(src, env)
}
}
module.exports = MarkdownIt;