view-markdown.js
2.4 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
75
76
77
78
79
80
/**
* view-markdown
* Created by lintry on 2018/1/9.
*/
const path = require('path'),
fs = require('fs-extra'),
ejs = require('ejs'),
juice = require('juice');
class ViewMarkdown {
/**
* 初始化markdown
* @param doc_path 文档所在路径
* @param options toc: 是否显示TOC default_md: 默认markdown文件名 theme: 默认主题 relative_path: css的相对路径(便于输出html)
*/
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 主题
* @param resource_base 资源根路径
* @return {string}
*/
render (filename, theme, resource_base) {
resource_base = resource_base || '';
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;
let inline = this.options.inline;
const template = fs.readFileSync(path.resolve(process.cwd(), (inline) ? 'src/inline-index.ejs' : 'src/index.ejs'), 'utf8');
let html = ejs.render(template, {
tittle,
theme,
content,
resource_base
}, {
root: process.cwd()
});
if (inline) {
let css = [
fs.readFileSync(path.resolve(process.cwd(), 'themes/markdown.css'), 'utf8'),
fs.readFileSync(path.resolve(process.cwd(), 'themes', theme, theme + '.css'), 'utf8')
].join('\n');
html = juice.inlineContent(html, css);
}
return html
}
}
module.exports = ViewMarkdown;