-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
88 lines (86 loc) · 2.24 KB
/
main.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
const http = require('http');
const fs = require("fs");
const url = require("url");
const server = http.createServer();
const HTTP_PORT = 3456;
/**
*
* @param {http.IncomingMessage} req request
* @param {http.ServerResponse} res response
* @param {string} url_path url路径部分
* @param {string} url_ext url扩展名
*/
const onGet= function(req,res,url_path,url_ext){
let contentType;
switch(url_ext){
case "html":{
contentType = "text/html";
break;
}
case "js":{
contentType = "text/javascript";
break;
}
case "css":{
contentType = "text/css";
break;
}
case "png":case "jpg":case "jpeg":case "gif":case "icon":{
contentType = `image/${url_ext}`;
break;
}
default:{
return false;
}
}
const filepath=`${__dirname}${url_path}`;
fs.exists(filepath,exists=>{
if(exists){
var file = fs.createReadStream(filepath);
res.writeHead(200, {'Content-Type' : contentType});
file.pipe(res);
}else{
output404(req,res,contentType);
}
});
return true;
}
/**
*
* @param {http.IncomingMessage} req
* @param {http.ServerResponse} res
*/
const output404 = (req,res,contentType)=>{
if(!contentType){
contentType = "text/plain";
}
res.setHeader("content-type",contentType);
res.statusCode = 404;
res.write('404,url=');
res.write(req.url);
res.end();
};
server.on('request',
(req,res)=>{
let url_path = url.parse(req.url).pathname;
if(url_path[url_path.length-1]==="/"){
url_path += "index.html";
}
let extindex = url_path.lastIndexOf(".");
let ext;
if(extindex===-1){
ext = "";
}else{
ext = url_path.substr(extindex+1).toLowerCase();
}
switch(req.method){
case "GET":{
if(onGet(req,res,url_path,ext))return;
break;
}
}
output404(req,res);
});
server.listen(HTTP_PORT,()=>{
console.log(`服务端已开启,访问地址 http://127.0.0.1:${HTTP_PORT}/ `);
});