-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathhttp-last-modified.js
More file actions
49 lines (44 loc) · 1.39 KB
/
Copy pathhttp-last-modified.js
File metadata and controls
49 lines (44 loc) · 1.39 KB
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
const http = require('http');
const url = require('url');
const path = require('path');
const fs = require('fs');
const mime = require('mime');
const server = http.createServer((req, res) => {
let filePath = path.resolve(__dirname, path.join('www', url.fileURLToPath(`file:///${req.url}`)));
console.log(`Request: ${filePath}`);
if(fs.existsSync(filePath)) {
const stats = fs.statSync(filePath);
if(stats.isDirectory()) {
filePath = path.join(filePath, 'index.html');
}
if(fs.existsSync(filePath)) {
const {ext} = path.parse(filePath);
const stats = fs.statSync(filePath);
const timeStamp = req.headers['if-modified-since'];
let status = 200;
if(timeStamp && Number(timeStamp) === stats.mtimeMs) {
status = 304;
}
res.writeHead(status, {
'Content-Type': mime.getType(ext),
'Cache-Control': 'max-age=86400', // 缓存一天
'Last-Modified': stats.mtimeMs,
});
if(status === 200) {
const fileStream = fs.createReadStream(filePath);
fileStream.pipe(res);
} else {
res.end();
}
}
} else {
res.writeHead(404, {'Content-Type': 'text/html'});
res.end('<h1>Not Found</h1>');
}
});
server.on('clientError', (err, socket) => {
socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
});
server.listen(10080, () => {
console.log('opened server on', server.address());
});