-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
119 lines (97 loc) · 2.59 KB
/
app.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
/**
* @file 简单web服务器
* @author Varsha
*/
import http from 'http';
import path from 'path';
import fs from 'fs';
import url from 'url';
http.createServer((req, res) => {
let pathname = url.parse(req.url, true).pathname;
if (pathname === '/') {
pathname = '/index.html';
}
let extname = path.extname(pathname);
if (extname.length === 0) {
// FIXME:非静态资源
res.end();
return;
}
let localPath = '.' + pathname; // 资源路径
resourceHandler(localPath, extname, req, res);
}).listen(8000);
const typeMap = {
html: 'text/html',
css: 'text/css',
js: 'text/js',
jpg: 'image/jpeg',
png: 'image/png',
pdf: 'application/pdf'
};
function resourceHandler(localPath, extName, req, res) {
fs.exists(localPath, exists => {
// 资源不存在
if (!exists) {
notFound(res);
return;
}
let head = {
'Content-Type': typeMap[extName.slice(1)]
};
// html不允许缓存
if (extName === '.html') {
head = {...head,
'Cache-Control': 'max-age=0',
'Expires': new Date(Date.now() - 3600000)
};
sendFile(localPath, head, res);
return;
}
// 非html资源,弱缓存验证
fs.stat(localPath, (err, stat) => {
if (err) {
serverError(res);
return;
}
let lastModified = stat.mtime;
let modifiedSince = req.headers['if-modified-since'];
// 请求文件未修改
if (modifiedSince && modifiedSince === '' + lastModified) {
notModified(res);
return;
}
let date = new Date();
date.setMinutes(date.getMinutes() + 10); // 过期时间
head = {
...head,
'Last-Modified': lastModified,
'Cache-Control': 'max-age=' + (10 * 60),
'Expires': date
};
sendFile(localPath, head, res);
});
});
}
// 200 OK
function sendFile(localPath, head, res) {
fs.readFile(localPath, (err, data) => {
res.writeHead(200, head);
res.write(data);
res.end();
});
}
// 304 Not Modified
function notModified(res) {
res.writeHead(304, 'Not Modified');
res.end();
}
// 404 Not Found
function notFound(res) {
res.writeHead(404, 'Not Found');
res.end();
}
// 500 Server Error
function serverError(res) {
res.writeHead(500, 'Server Error');
res.end();
}