-
Notifications
You must be signed in to change notification settings - Fork 0
/
2.js
64 lines (61 loc) · 1.66 KB
/
2.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
var http = require("http");
var url = require("url");
var fs = require("fs");
var path = require("path");
function funGetType(filePath){
var contentType = "";
var ext = path.extname(filePath);
switch(ext){
case ".html":
contentType = "text/html";
break;
case ".js":
contentType = "text/javascript";
break;
case ".css":
contentType = "text/css";
break;
case ".jpg":
contentType = "image/jpeg";
break;
default:
contentType = "application/octet-stream";
break;
}
return contentType;
}
function webServer(req,res){
var requrl = req.url;
var pathName = url.parse(requrl).pathname;
var pathExtName = path.extname(pathName);
if(pathExtName == ""){
pathName = "/";
}
if(pathName.charAt(pathName.length - 1) == "/"){
pathName +="index.html";
}
var fileName = pathName.slice(1);
console.log("path:" + pathName);
console.log("extend:" + pathExtName);
console.log("filePath:" + fileName);
fs.exists(fileName,function(exists){
if(exists){
res.writeHead(200,{"Content-Type":funGetType(fileName)});
var stream = fs.createReadStream(fileName,{flag:"r",encoding:null});
stream.on("error",function(){
res.end("<h1>error occured!</h1");
});
stream.pipe(res);
}else {
res.writeHead(404,{"Content-Type":"text/html"});
res.end("<h1>404 Not Found</h1>");
}
});
}
var newWebSvr = http.createServer(webServer);
newWebSvr.on("error",function(error){
console.log("Error: " + error);
});
newWebSvr.listen(9000,function(){
console.log("The server is running on port 9000");
});