forked from jmpressjs/docs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
_generate.js
91 lines (84 loc) · 2.09 KB
/
_generate.js
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
81
82
83
84
85
86
87
88
89
90
91
var fs = require("fs");
var path = require("path");
var https = require("https");
var files = fs.readdirSync(__dirname)
.filter(function(file) {
return /^[^README]*\.md$/.test(file);
})
.map(function(file) {
var name = file.replace(/\.md$/, "");
return {
name: name,
mdFile: path.join(__dirname, file),
htmlFile: path.join(__dirname, name + ".html")
}
});
// Render markdown
var count = files.length;
files.forEach(function(file) {
fs.readFile(file.mdFile, "utf-8", function(err, mdContent) {
if(err) throw err;
try {
var marked = require("marked");
marked.setOptions({
gfm: true,
pedantic: true
});
onResponse(marked(mdContent));
} catch(e) {
var reqContent = JSON.stringify({
text: mdContent,
mode: "gfm",
context: "jmpressjs/docs"
});
var opt = require("url").parse("https://api.github.com/markdown");
opt.headers = {
accept: "application/vnd.github.beta+json",
host: "api.github.com",
"user-agent": "NodeJS HTTP Client",
"content-length": reqContent.length,
"content-type": "application/json"
};
opt.method = "POST";
var req = https.request(opt, function(res) {
res.setEncoding("utf-8");
if(res.statusCode != 200) {
console.error("statusCode should be 200, but is " + res.statusCode);
console.dir(res.headers);
return;
}
var arr = [];
res.on("data", arr.push.bind(arr));
res.on("end", function() {
onResponse(arr.join(""));
});
}).on("error", function(err) {
console.error(err);
});
req.write(reqContent, "utf-8");
req.end();
}
});
function onResponse(html) {
file.html = html;
done();
}
});
function done() {
if(--count == 0)
writeOut();
}
function writeOut() {
fs.readFile(path.join(__dirname, "_template._html"), "utf-8", function(err, template) {
if(err) throw err;
files.forEach(function(file) {
var content = template;
Object.keys(file).forEach(function(key) {
content = content.replace('{{' + key + '}}', file[key]);
});
fs.writeFile(file.htmlFile, content, "utf-8", function(err) {
if(err) throw err;
});
});
});
}