-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
49 lines (48 loc) · 1.11 KB
/
server.js
File metadata and controls
49 lines (48 loc) · 1.11 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
var http = require('http');
var fs = require('fs');
var path = require('path');
var mime = require('mime');
var cache = {};
var route = require('./lib/route');
function send404(res) {
res.writeHead(404, {'Content-Type':'text/plain'});
res.write('请求无效');
res.end();
}
function sendFile(res, filePath, fileContents) {
res.writeHead(200, {'Content-Type': mime.lookup(path.basename(filePath))});
res.end(fileContents);
}
function serverStatic(res, cache, absPath) {
if(cache[absPath]) {
sendFile(res, absPath, cache[absPath]);
} else {
fs.exists(absPath, function(exists) {
if(exists) {
fs.readFile(absPath, function(err, data) {
if(err) {
send404(res);
} else {
cache[absPath] = data;
sendFile(res, absPath, data);
}
});
} else {
send404(res)
}
})
}
}
function serverStart(req, res) {
var url = req.url;
if(route.route[url]) {
var absPath = './' + route.route[url];
serverStatic(res, cache, absPath);
} else {
send404(res);
}
}
var server = http.createServer(serverStart);
var chat = require('./lib/chat');
chat.listen(server);
server.listen(8999);