建站服务器
1

2
3
4
5
6
7
8
//http协议模块
varhttp = require(\'http\');
//url解析模块
varurl = require(\'url\');
//文件系统模块
varfs = require(fs);
//路径解析模块
varpath = require(path);
1
2
3
4
5
6
7
8
//创建一个服务
varhttpServer = http.createServer(this.proce***equest.bind(this));
//在指定的端口监听服务
httpServer.listen(port,function(){
console.log([HttpServer][Start],runing at http://+ip+:+port+/);
console.timeEnd([HttpServer][Start]);
});
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
proce***equest:function(request,response){
varhasExt =true;
varrequestUrl = request.url;
varpathName = url.parse(requestUrl).pathname;
//对请求的路径进行解码,防止中文乱码
pathName = decodeURI(pathName);
//如果路径中没有扩展名
if(path.extname(pathName) ===\'\'){
//如果不是以/结尾的,加/并作301重定向
if(pathName.charAt(pathName.length-1) !=/){
pathName +=/;
varredirect =http://+request.headers.host + pathName;
response.writeHead(301, {
location:redirect
});
response.end();
}
//添加默认的访问页面,但这个页面不一定存在,后面会处理
pathName +=index.html;
hasExt =false;//标记默认页面是程序自动添加的
}
//获取资源文件的相对路径
varfilePath = path.join(http/webroot,pathName);
//获取对应文件的文档类型
varcontentType =this.getContentType(filePath);
//如果文件名存在
fs.exists(filePath,function(exists){
if(exists){
response.writeHead(200, {content-type:contentType});
varstream = fs.createReadStream(filePath,{flags:r,encoding:null});
stream.on(error, function() {
response.writeHead(500,{content-type:text/html});
response.end(500 Server Error
);
});
//返回文件内容
stream.pipe(response);
}else{//文件名不存在的情况
if(hasExt){
//如果这个文件不是程序自动添加的,直接返回404
response.writeHead(404, {content-type:text/html});
response.end(404 Not Found
);
}else{
//如果文件是程序自动添加的且不存在,则表示用户希望访问的是该目录下的文件列表
varhtml =;
try{
//用户访问目录
varfiledir = filePath.substring(0,filePath.lastIndexOf(\'\\\\\'));
//获取用户访问路径下的文件列表
varfiles = fs.readdirSync(filedir);
//将访问路径下的所以文件一一列举出来,并添加超链接,以便用户进一步访问
for(variinfiles){
varfilename = files[i];
html +=;
}
}catch(e){
html +=您访问的目录不存在
}
response.writeHead(200, {content-type:text/html});
response.end(html);
}
}
});
}