-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
89 lines (82 loc) · 2.46 KB
/
index.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
const http = require("http");
const fs = require("fs");
const path = require("path");
const { URL } = require("url");
const util = require("util");
const readFile = util.promisify(fs.readFile);
const crypto = require("crypto");
function fileMd5(file) {
const hash = crypto.createHash("md5");
hash.update(file);
return hash.digest("hex");
}
function getContentType(ext) {
return ext === ".js" ? "application/javascript" : ext === ".html" ? "text/html" : "text/html";
}
const staticServer = http.createServer(function(req, res) {
const url = new URL(`http://localhost:8081${req.url}`);
const filePath = path.join(__dirname, "static", url.pathname);
// 文件不存在
if (!fs.existsSync(filePath)) {
res.statusCode = 404;
return res.end();
}
const fileStat = fs.statSync(filePath);
// 目录
if (fileStat.isDirectory()) {
res.statusCode = 404;
return res.end();
}
const ext = path.extname(filePath);
// Etag
const ETag = fileMd5(JSON.stringify(fileStat));
// Last-Modified
const lastModified = new Date(fileStat.mtimeMs).toGMTString();
if (req.headers["if-none-match"] === ETag || req.headers["if-modified-since"] === lastModified) {
res.writeHead(304, {
"Content-Type": getContentType(ext),
"Cache-Control": "no-cache",
Connection: "keep-alive",
ETag,
"Last-Modified": lastModified
});
return res.end();
}
// 200 ok
readFile(filePath, "utf-8").then(file => {
res.writeHead(200, {
"Content-Type": getContentType(ext),
"Cache-Control": "no-cache",
Connection: "close",
ETag,
"Last-Modified": lastModified
});
const time = url.searchParams.get("time");
if (time) {
setTimeout(() => res.end(file), parseInt(time));
} else {
res.end(file);
}
});
});
const ajaxServer = http.createServer(function(req, res) {
const url = new URL(`http://localhost:8081${req.url}`);
switch (url.pathname) {
case "/cache":
res.writeHead("200", {
"Content-Type": "application/json;",
"Access-Control-Allow-Origin": "http://localhost:8081",
"Access-Control-Allow-Headers": "*",
"Access-Control-Allow-Methods": "*",
"Access-Control-Max-Age": 10000
});
return res.end('console.log("Hello Wrold")');
}
return res.end("Hello World");
});
staticServer.listen(8081, () => {
console.log("start:http://localhost:8081/");
});
ajaxServer.listen(8082, () => {
console.log("start:http://localhost:8082/");
});