Use Nodejs to build a simple Web server

Source: Internet
Author: User

Using Nodejs to build a Web server is a comprehensive introductory tutorial for node. js, because to complete a simple Web server, you need to learn some of the more important modules in Nodejs, such as: HTTP protocol module, file system, URL parsing module, path parsing module, and the 301 redirect problem, let's talk a little bit about 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:

// HTTP Protocol Module var http = require (' http '); // URL Parsing module var url = require (' URL '); // File System Module var fs = require ("FS"); // Path Parsing module var path = require ("path");

Create the service and listen on the specified port:

// Create a service var httpserver = Http.createserver (this. Processrequest.bind (this)); // on the specified port, listen for service 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. Request is used to set the response header and respond to the client.

ProcessRequest:function(request,response) {varHasext =true; varRequesturl =Request.url; varPathName =Url.parse (requesturl). Pathname; //decoding the requested path to prevent Chinese garbled charactersPathName =decodeURI (pathName); //if the path does not have a name extension    if(Path.extname (pathName) = = = "){        //if not at/end, add/and make 301 redirect        if(Pathname.charat (pathname.length-1)! = "/") {PathName+= "/"; varREDIRECT = "http//" +request.headers.host +PathName; Response.writehead (301, {location:redirect});        Response.End (); }        //The default access page is added, but the page does not exist and will be processed laterPathName + = "index.html"; Hasext=false;//tag default page is automatically added by program    }    //gets the relative path of the resource file    varFilePath = Path.join ("Http/webroot", PathName); //gets the document type of the corresponding file    varContentType = This. getContentType (FilePath); //if the file name existsFs.exists (FilePath,function(exists) {if(exists) {Response.writehead ($, {"Content-type": ContentType}); varstream = Fs.createreadstream (filepath,{flags: "R", encoding:NULL}); Stream.on ("Error",function() {Response.writehead (500,{"Content-type": "Text/html"}); Response.End (");            }); //Return file Contentsstream.pipe (response); }Else{//case where the file name does not exist            if(hasext) {//If this file is not automatically added by the program, return directly to 404Response.writehead (404, {"Content-type": "Text/html"}); Response.End ("); }Else {                //If the file is automatically added by the program and does not exist, it means that the user wants to access the list of files in that directory                varhtml = "; Try{                    //user access to directory                    varFiledir = filepath.substring (0,filepath.lastindexof (' \ \ '))); //get a list of files under the user access path                    varFiles =Fs.readdirsync (Filedir); //list all the files under the Access path and add hyperlinks for further user access                     for(varIinchfiles) {                        varfilename =Files[i]; HTML+ = "<div><a href=" "+filename+" > "+filename+" </a></div> "; }                }Catch(e) {HTML+ = "} response.writehead ($, {"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

The core code is so much, about 140 lines, the complete code has been uploaded to the Git:https://github.com/git-onepixel/node,

View Demo: http://onepixel.top:8888/

If you have any questions, you are welcome to discuss!

Use Nodejs to build a simple 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.