Using Nodejs to build a Web server

Source: Internet
Author: User

Building a Web server using Nodejs is a comprehensive introductory tutorial for node. js because implementing a Web server requires several more important modules in Nodejs: HTTP protocol module, file system, URL parsing module, path parsing module, and 301 redirect technology, Let's learn how to build a simple Web server.

As a Web server, you should have the following features:

1, can display the end of the. html/.htm Web page

2, can open the file content that ends with. Js/.css/.json/.text directly

3. Display Picture Resources

4. Automatically download files ending with. apk/.docx/.zip

5, shape, such as http://xxx.com/a/b/, then look for the B directory whether there is index.html, if there is a display, if not listed in the directory of all files and folders, and can be further accessed.

6, shape as http://xxx.com/a/b, then 301 redirect to http://xxx.com/a/b/, this can solve internal resource reference dislocation problem.

Introduce several modules that need to be used:

1

2

3

4

5

6

7

8

//http协议模块

varhttp = require(‘http‘);

//url解析模块

varurl = require(‘url‘);

//文件系统模块

varfs = require("fs");

//路径解析模块

varpath = require("path");

Create the service and listen on the specified port:

1

2

3

4

5

6

7

8

//创建一个服务

varhttpServer = http.createServer(this.processRequest.bind(this));

//在指定的端口监听服务

httpServer.listen(port,function(){

    console.log("[HttpServer][Start]","runing at http://"+ip+":"+port+"/");

    console.timeEnd("[HttpServer][Start]");

});

  

When creating a service, you need to pass an anonymous function processrequest the request, ProcessRequest receives 2 parameters, the request and response, which contains all of the requested content. The response is used to set the response header and respond to the client.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21st

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

processRequest: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(");

            });

            //返回文件内容

            stream.pipe(response);

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

            if(hasExt){

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

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

                response.end(");

            }else{

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

                varhtml = ";

                try{

                    //用户访问目录

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

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

                    varfiles = fs.readdirSync(filedir);

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

                    for(varinfiles){

                        varfilename = files[i];

                        html += "<div><a  href=‘"+filename+"‘>"+filename+"</a></div>";

                    }

                }catch(e){

                    html += "

                }

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

                response.end(html);

            }

        }

    });

}

  

There are a few key points in the request handling function that need to be said:

For Chinese in the path, the browser will automatically encode (English unchanged, Chinese will change), so after receiving the address, the address needs to be decoded, or the last obtained path and the actual path does not match,

When the access path is not at the end of a specific file and is not at/end, you will need to redirect plus/to represent the current directory, otherwise static resources under the current path cannot be found

If the access path is a directory, then list all files and folders in that directory, and can click Access, in order for the Chinese directory to display correctly, then also set the Charset=utf-8 in the header

650) this.width=650; "Src=" http://images2015.cnblogs.com/blog/849589/201603/849589-20160328011923301-1535120885. PNG "width=" 459 "height=" 219 "style=" border:0px; "/>

The core code is so much, about 140 lines, the complete code has been uploaded to the gi th u b:ht T P S://G i th u b. C om/g I t-on Epixel/node,

If you want to run the demo, open cmd to switch to the root directory and run node start.



Using Nodejs to build a Web server

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.