view-markdown.js
1.74 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
/**
* 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;