Nodejs builds simple Web server details and examples, nodejsweb

Source: Internet
Author: User

Nodejs builds simple Web server details and examples, nodejsweb

Use Nodejs to build a simple Web Server

Using Nodejs to build a Web server is to learn Node. js is a comprehensive introductory tutorial. To complete a simple Web server, you need to learn several important modules in Nodejs, such: the http protocol module, file system, url parsing module, path parsing module, and 301 redirection problems. Next we will briefly explain how to build a simple Web server.

As a Web server, you must have the following functions:

1 Tib displays Web pages ending with .html/. htm

2. You can directly open the file content ending with. js/. css/. json/. text.

3. display image resources

4、automatically downloads files ending with .apk/. docx/. zip

5, such as http://xxx.com/a/ B/, then find the directory B contains index.html, if there is show, if not, list all the files and folders under the directory, and further access.

6, such as http://xxx.com/a/ B, 301 redirection to the http://xxx.com/a/ B/, this can solve the internal resource reference dislocation problem.

Introduce the following modules:

// Http 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 a service and listen on the specified port:

// Create a service var httpServer = http. createServer (this. processRequest. bind (this); // listen to the service httpServer on the specified port. listen (port, function () {console. log ("[HttpServer] [Start]", "runing at http: //" + ip + ":" + port + "/"); console. timeEnd ("[HttpServer] [Start]") ;});

When creating a service, you must pass an anonymous function processRequest to process the request. processRequest receives two parameters: request and response. The request object contains all the content of the request, response is used to set the response header and respond to the client.

ProcessRequest: function (request, response) {var hasExt = true; var requestUrl = request. url; var pathName = url. parse (requestUrl ). pathname; // decodes the Request path to prevent Chinese garbled pathName = decodeURI (pathName); // if the path does not have an extension if (path. extname (pathName) = '') {// if it does not end with a slash (/), add the slash (/) and perform 301 redirection if (pathName. charAt (pathName. length-1 )! = "/") {PathName + = "/"; var redirect = "http: //" + request. headers. host + pathName; response. writeHead (301, {location: redirect}); response. end () ;}// Add the default access page, but this page does not necessarily exist. pathName + = "index.html"; hasExt = false; // mark the default page as automatically added by the program} // obtain the relative path of the resource file var filePath = path. join ("http/webroot", pathName); // obtain the file type var contentType = this. getContentType (filePath); // if the file name exists fs. exists (filePath, function (exists) {if (exists) {response. writehead( 200, {"content-type": contentType}); 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 key points in the request processing function:

If the path contains Chinese characters, the browser will automatically encode the code (English remains unchanged, and Chinese characters will change). Therefore, after receiving the address, you need to decode the address, otherwise, the obtained path does not match the actual path,

When the access path does not end with a specific file and does not end with a slash (/), add a slash (/) to indicate the current directory. Otherwise, the static resources in the current path cannot be found.

If the access path is a directory, all files and folders under the directory are listed, and you can click access. To make the Chinese directory display properly, set charset = UTF-8 in the header.

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

To run the demo, open cmd to switch to the root directory and run node start.

If you have any questions, please discuss them!

Thank you for reading this article. I hope it will 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.