-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathblog.js
88 lines (77 loc) · 2.16 KB
/
blog.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
"use strict";
const http = require("http");
const url = require("url");
const path = require("path");
require("./lib/hijack_console");
const loadFiles = require("./lib/load_files");
function extractIp(req) {
return (req.socket.remoteAddress);
}
function getArticle(req, res) {
if (req.url === "/") req.url = "/mds/index.md";
const pathname = decodeURIComponent(url.parse(req.url).pathname);//解码包含包含中文的url
showContent(req, res, pathname);
}
const notModified = function (req, content) {
const eTag = req.headers["if-none-match"];
if (eTag === content.eTag) {
//console.log("eTag相等", eTag);
return true;
} else {
return false;
}
};
const getContentType = function (pathname) {
let extendName = require("path").extname(pathname);
if (extendName.endsWith(".md")) {
extendName = extendName.replace(".md", ".html");
}
return require("mime-types").contentType(extendName);
}
async function showContent(req, res, pathname, type) {
let content = await loadFiles.getByPathname(path.join(__dirname, pathname));
if (!content) {
console.warn("404 in ", type);
show404(req, res);
} else if (notModified(req, content)) {
show304(req, res);
} else {
res.setHeader("Content-Type", getContentType(pathname));
res.setHeader("Etag", content.eTag);
res.end(content.content);
}
}
function show404(req, res) {
console.error(`非法路径请求${req.url},来源是`, extractIp(req));
res.statusCode = 404;
res.end();
}
function show304(req, res) {
// console.warn(`资源没有改变${req.url}`);
res.statusCode = 304;
res.end();
}
async function watchDir() {
await require("./lib/monitor")(path.join(__dirname, "./mds"));
await require("./lib/monitor")(path.join(__dirname, "./css"));
await require("./lib/monitor")(path.join(__dirname, "./imgs"));
}
function startServer() {
const port = 8888;
const server = http.createServer(getArticle);
server.listen(port, ()=>{
console.log("服务器启动,监听端口", port);
});
}
async function start() {
try {
await watchDir();
startServer();
} catch (e) {
console.error(e);
}
}
process.on("uncaughtException", (error, source) => {
console.log("uncaughtException", error, source)
});
start();