实现步骤
- 通过fs文件模块watchFile事件监听md文件的修改
- 通过fs文件模块readFile方法读取md文件内容
- 把md文件内容通过marked模块转为html内容
- 创建html页面骨架
- 把转换好的html内容填充到页面骨架
- 通过request模块请求外部github-markdown.css文件
- 把css内容填充到html页面骨架里的style里
- 通过fs文件模块writeFile方法写入全部内容并创建html文件
源代码
class Md2Html {
constructor(fileName) {
this.fs = require('fs');
this.path = require('path');
this.marked = require('marked');
this.request = require('request');
this.fileName = fileName || 'unnamed';
this.target = this.path.join(__dirname) + '/' + this.fileName + '.md';
this.watchFile();
}
watchFile() {
this.fs.watchFile(this.target, {
persistent: true,
interval: 200,
}, (curr, prev) => {
if (curr.mtime == prev.mtime) {
return false;
}
this.fs.readFile(this.target, 'utf-8', (err, data) => {
if (err) {
throw err;
}
const html = this.marked(data);
let template = this.createTemplate();
template = template.replace('{{{content}}}', html);
this.createMarkdownCss(css => {
template = template.replace('{{{style}}}', css);
this.createFile(template);
});
});
});
}
createTemplate() {
const template = `<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" >
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>md文件转html页面</title>
<style>
.markdown-body {
box-sizing: border-box;
min-width: 200px;
max-width: 980px;
margin: 0 auto;
padding: 45px;
}
@media (max-width: 767px) {
.markdown-body {
padding: 15px;
}
}
{{{style}}}
</style>
</head>
<body>
<article class="markdown-body">
{{{content}}}
</article>
</body>
</html>`;
return template;
}
createMarkdownCss(fn) {
var url = 'https://cdnjs.cloudflare.com/ajax/libs/github-markdown-css/3.0.1/github-markdown.min.css';
this.request(url, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
fn && fn(body);
}
});
}
createFile(content) {
const name = this.fileName;
const suffix = 'html';
const fullName = name + '.' + suffix;
const file = this.path.join(__dirname, fullName);
this.fs.writeFile(file, content, 'utf-8', err => {
if (err) {
throw err;
}
console.log('写入成功!');
});
}
}
new Md2Html('README');