forked from igorw/buster-docs
/
server.js
92 lines (83 loc) · 2.95 KB
/
server.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
92
var http = require("http");
var fs = require("fs");
var path = require("path");
var url = require("url");
var mime = require("mime");
var ejs = require("ejs");
var PUBLIC = path.join(__dirname, "public");
var SITE = path.join(__dirname, "site");
var LAYOUT = fs.readFileSync(path.join(__dirname, "layout.html"), "utf8");
function serveFile(path, res) {
fs.readFile(path, function (err, data) {
res.writeHead(200, {"Content-Type": mime.lookup(path)});
res.write(data);
res.end();
});
}
function serveTemplate(path, pathname, res) {
if (pathname.slice(pathname.length - 1) == "/") {
res.writeHead(200, {"Content-Type": "text/html"});
fs.readFile(path, function (err, data) {
res.write(renderTemplate(pathname, data.toString("utf8")));
res.end();
});
} else {
res.writeHead(301, {"Location": pathname + "/"});
res.end();
}
}
function renderTemplate(pathname, content) {
var menu = [
{href: "/", text: "Home"},
{href: "/docs/", text: "Documentation", matcher: /^\/docs/},
{href: "/community/", text: "Community"}
];
menu.forEach(function (item) {
var current = item.matcher ? item.matcher.test(pathname) : pathname == item.href;
if (current) item.className = "active";
});
return ejs.render(LAYOUT, {content: content, menu: menu});
}
function notFound(res) {
res.writeHead(404);
res.write("404 Page Not Found");
res.end();
}
var server = http.createServer(function (req, res) {
var u = url.parse(req.url);
var pubFilePath = path.join(PUBLIC, u.pathname);
fs.stat(pubFilePath, function (err, stat) {
if (err || !stat.isFile()) {
var dirPath = path.join(SITE, u.pathname);
fs.stat(dirPath, function (err, stat) {
if (!err && stat.isDirectory()) {
var indexHtmlPath = path.join(dirPath, "index.html");
fs.stat(indexHtmlPath, function (err, stat) {
if (err || !stat.isFile()) {
notFound(res);
} else {
serveTemplate(indexHtmlPath, u.pathname, res);
}
});
} else {
var templatePath = dirPath.slice(0, dirPath.length - 1) + ".html";
fs.stat(templatePath, function (err, stat) {
if (!err && stat.isFile()) {
serveTemplate(templatePath, u.pathname, res);
} else {
notFound(res);
}
});
}
});
} else {
serveFile(pubFilePath, res);
}
});
});
exports.start = function (port) {
port = port || parseInt(process.argv[2], 10) || 8090;
server.listen(port);
console.log("Listening on http://127.0.0.1:" + port);
return server;
};