使用Nodejs搭建Web服务器

建站服务器

1

延庆网站建设公司创新互联,延庆网站设计制作,有大型网站制作公司丰富经验。已为延庆1000+提供企业网站建设服务。企业网站搭建\外贸网站制作要多少钱,请找那个售后服务好的延庆做网站的公司定做!

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(<h2>500 Server Error</h2>);

});

//返回文件内容

stream.pipe(response);

}else{//文件名不存在的情况

if(hasExt){

//如果这个文件不是程序自动添加的,直接返回404

response.writeHead(404, {content-type:text/html});

response.end(<h2>404 Not Found</h2>);

}else{

//如果文件是程序自动添加的且不存在,则表示用户希望访问的是该目录下的文件列表

varhtml =<head><meta charset=\'utf-8\'></head>;

try{

//用户访问目录

varfiledir = filePath.substring(0,filePath.lastIndexOf(\'\\\\\'));

//获取用户访问路径下的文件列表

varfiles = fs.readdirSync(filedir);

//将访问路径下的所以文件一一列举出来,并添加超链接,以便用户进一步访问

for(variinfiles){

varfilename = files[i];

html +=<div><a href=\'+filename+\'>+filename+</a></div>;

}

}catch(e){

html +=<h2>您访问的目录不存在</h2>

}

response.writeHead(200, {content-type:text/html});

response.end(html);

}

}

});

}

新闻标题:使用Nodejs搭建Web服务器
文章位置:https://www.cdcxhl.com/article2/cpeoic.html

成都网站建设公司_创新互联,为您提供网站排名微信小程序标签优化搜索引擎优化移动网站建设网站收录

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

成都网站建设公司