-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy path5.server.js
31 lines (29 loc) · 1.08 KB
/
5.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
var http = require("http");
//获取fs模块
var fs = require("fs");
var mime = require('mime');
//通过http的createServer方法创建一个http服务器
var server = http.createServer(function (request, response) {
if (request.url == '/clock') {
response.end(new Date().toString());
} else {
//如果请求的URL是 /index.html的话,
//读到文件的内容,并指定编码。
//判断文件是否存在
fs.exists(request.url.slice(1), function (exists) {
if (exists) {
response.setHeader('Content-Type', mime.lookup(request.url));
fs.readFile(request.url.slice(1), "utf8", function (err, data) {
//当文件读取成功之后,调用回调函数,
//把读到的文件内容写入到响应体里
response.write(data);
//关闭和客户端的响应了
response.end();
});
} else {
response.end('404');
}
})
}
});
server.listen(8080);