forked from xiamaoxialeyan/My.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
53 lines (46 loc) · 1.63 KB
/
server.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
//****************************************************\\
//*****************Node.js Web服务器*****************\\
//******在命令行中运行 node server.js 启动服务器******\\
//****************************************************\\
var http = require('http');
var url = require('url');
var fs = require('fs');
var mine = require('./mine').types;
var path = require('path');
var vhost = require('vhost');
function handle(req, res) {
var pathname = url.parse(req.url).pathname;
pathname && (pathname = pathname.slice(1));
console.log(pathname);
var ext = path.extname(pathname);
ext = ext ? ext.slice(1) : 'unknown';
fs.exists(pathname, function(exists) {
if (!exists) {
res.writeHead(404, {
'Content-Type': 'text/plain'
});
res.write('Not Found');
res.end();
} else {
fs.readFile(pathname, "binary", function(err, file) {
if (err) {
res.writeHead(500, {
'Content-Type': 'text/plain'
});
res.end(err);
} else {
res.writeHead(200, {
'Content-Type': req.headers['content-type'] || mine[ext] || 'text/plain'
});
res.write(file, 'binary');
res.end();
}
});
}
});
}
var next = vhost('lib.dodo.com.cn', handle);
var server = http.createServer(function(req, res) {
next(req, res);
}).listen(8888, 'lib.dodo.com.cn');
console.log('Server running at http://lib.dodo.com.cn:8888');