Nodejs build a simple Web server and a detailed example _node.js

Source: Internet
Author: User

Using Nodejs to build a simple Web server

Using Nodejs to build a Web server is a comprehensive introductory tutorial for learning Node.js, because to complete a simple Web server, you need to learn some of the more important NODEJS modules, such as: HTTP protocol module, file system, URL parsing module, path resolution module, and 301 redirect issues, 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 directly open to. Js/.css/.json/.text end of the contents of the file

3. Display Picture Resources

4, automatically download to. Apk/.docx/.zip End of the file

5, like http://xxx.com/a/b/, then look for B directory whether there are index.html, if there is, if not listed in the directory of all files and folders, and can further access.

6, the shape such as http://xxx.com/a/b, then make 301 Redirect to http://xxx.com/a/b/, this can solve the 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 Resolution module
var path = require ("path");

To create a service and listen on the specified port:

Create a service
var httpserver = Http.createserver (This.processRequest.bind (this));

Listens for service Httpserver.listen on the specified port (
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, request and response, which contains all of the requested content. Response is used to set up the response headers and to respond to the client.

Processrequest:function (request,response) {var hasext = true;
  var requesturl = Request.url;

  var pathName = Url.parse (requesturl). PathName;

  Decoding the path of the request to prevent Chinese garbled pathName = decodeURI (pathName);  If the path does not have an extension of if (path.extname (pathName) = = "") {//If not at/end, add/And make a 301 redirect if (Pathname.charat (pathname.length-1)!=
      "/") {PathName = "/";
      var redirect = "http://" +request.headers.host + pathName;
      Response.writehead (Location:redirect});
    Response.End ();
    //Add the default access page, but this page does not necessarily exist, the following will deal with pathName + = "index.html"; Hasext = false;

  Mark default page is program automatically added}//Get resource file relative path var filePath = Path.join ("Http/webroot", pathName);

  Gets the document type of the corresponding file var contentType = This.getcontenttype (FilePath); If the filename exists fs.exists (filepath,function (exists) {if (exists) {response.writehead: Content-type
      });
      var stream = Fs.createreadstream (filepath,{flags: "R", Encoding:null}); Stream.on ("Error", function () {Response.writehead (500,{"Content-type": "Text/html"});
      Response.End (" 

There are several points in the request processing 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, you need to decode the address, otherwise the end of the path and the true path does not match,

When the access path is not at the end of a specific file and is not in/ending, it needs to be redirected plus/, indicating the current directory, otherwise the static resources under the current path will not be found

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

The core code is so much, about 140 lines, the complete code has been uploaded to Http://xiazai.jb51.net/201611/yuanma/Node-master (jb51.net). rar

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

If you have any questions, please feel free to discuss!

Thank you for reading, I hope to help you, thank you for your support for this site!

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.