Node. js: creating simple Web Servers

Source: Internet
Author: User
In this chapter, we also use Node. js to build a simple Web server if you are familiar with it. NET or other similar platforms for Web development, you may create a Web server, create a Web project in Visual Studio, and click Run. This is indeed the case, but do not forget that the price is that you use it. NET Web application development, you use the complete IIS as the basis of your Web server, so that when your application is published, you can only use IIS. If you use an independent server (using System. web. if Hosting is built on your own), you must handle various HttpListener and corresponding threads, which will be troublesome, after all. NET is not Web-oriented. Node. js provides a convenient and customizable way for you to build a sophisticated and fully application-oriented service platform based on it.


1. Creating a simple Web server involves some basic knowledge points of Node. js:

1. Request Module
In Node. js, the system provides many useful modules (of course, you can also write your own modules in JavaScript. We will explain in detail in the following sections), such as http and url. The module encapsulates specific functions and provides corresponding methods or attributes. To use these modules, you must first request the module to obtain its operation objects.

For example, to use the system's http module, you can write as follows:

Var libHttp = require ('http'); // request the http protocol module

In this way, future programs can access the http module functions through the variable libHttp. This chapter uses the following system modules:
Http: server and client implementation that encapsulates the http protocol;
Url: parses and processes the url;
Fs: encapsulate the file system operation functions;
Path: encapsulate the path parsing function.
With these modules, we can build our own applications on the shoulders of giants.
2. Console
To better observe program running and view errors when exceptions occur, you can use the console function in the variable console.

Console. log ('this is a piece of log information'); timing and output timing information on the console: // start timing console. timeEnd ('timer 1'); // start the timer named "timer 1 ......... // end the timer and output it to the console. timeEnd ('timer 1'); // end the timer called "timer 1" and Output

3. define functions
In Node. the method for defining functions in js is exactly the same as that in common JavaScript. However, we recommend that you write the following code: Use a variable to name the function, this makes it easier to pass functions as parameters to other functions:

// Define a function named showErr var showErr = function (msg) {var inf = "error! "+ Msg; console. log (inf + msg); return msg ;}

4. Create a Web server and listen for access requests
The most important thing to create a Web server is to provide the Web request response function. It has two parameters: the first parameter indicates the information of the client request and the other parameter indicates the information to be returned to the client. The response function should parse the request information and assemble the returned content based on the request.

// Request module var libHttp = require ('HTTP '); // http module // The main function of the Web server, which parses the request and returns the Web content var funWebSvr = function (req, res) {res. writeHead (200, {'content-type': 'text/html'}); res. write (''); Res. write (' *** Node. js *** '); res. write ('Hello! '); Res. end ('');} // Create an http server var webSvr = libHttp. createServer (funWebSvr); // start listening to port 8124 webSvr. listen (8124 );

5. parse Web requests
For simple Web page access requests, important information is contained in the url of the Request Information Parameter. We can use the url parsing module to parse the access path in the url and use the path module, assemble the access path into the actual file path to be accessed for return.

Var reqUrl = req. url; // obtain the requested url // output the requested url to the console. log (reqUrl); // use the url parsing module to obtain the path name var pathName = libUrl in the url. parse (reqUrl ). pathname; // use the path module to obtain the extension if (libPath. extname (pathName) = "") {// if the path does not have the extension pathName + = "/"; // specify the Access Directory} if (pathName. charAt (pathName. length-1) = "/") {// If you access the directory pathName + = "index.html"; // specify as the default webpage} // use the path parsing module, assemble the actual file path var filePath = libPath. join (". /WebRoot ", pathName );

6. Set the return Header
Because it is a Web request, you need to include the http return header in the returned content. The focus here is to set the content type of the http return header Based on the file extension of the file path to be accessed.

Var contentType = ""; // use the path parsing module to obtain the file extension var ext = libPath. extname (filePath); switch (ext) {case ". html ": contentType =" text/html "; break; case ". js ": contentType =" text/javascript "; break ;...... default: contentType = "application/octet-stream";} // write the content type res in the return header. writehead( 200, {"Content-Type": contentType });

7. Write the accessed file content to the returned object
With the actual path of the file to be accessed and the content type corresponding to the file, you can use the fs file system module to read the file stream and return it to the client.

// Determine whether the file contains libPath. exists (filePath, function (exists) {if (exists) {// file exists // write content type res in the return header. writeHead (200, {"Content-Type": funGetContentType (filePath)}); // create a read-only stream to return var stream = libFs. createReadStream (filePath, {flags: "r", encoding: null}); // specifies that if the stream reading error occurs, the system returns the 404 error stream. on ("error", function () {res. writehead( 404); res. end ("404 Read Error") ;}); // connects the file stream and the http returned stream pipeline to return the actual Web content stream. pipe (res);} else {// the file does not exist // Error 404 res is returned. writehead( 404, {"Content-Type": "text/html"}); res. end ("404 Not Found ");}});

Ii. Testing and running
1. complete source code
The following 100 lines of JavaScript are the full source code of a simple web Server:

// ------------------------------------------------ // WebSvr. js // a demo Web Server // ------------------------------------------------------ // start the service timer console. time ('[WebSvr] [Start]'); // request module var libHttp = require ('http '); // HTTP module var libUrl = require ('url'); // url parsing module var libFs = require ("fs "); // file system module var libPath = require ("path"); // path parsing module // obtain the returned content type String Based on the path, var funGetContentType = function (filePath) {var contentType = ""; // use the path parsing module to obtain the file extension var ext = libPath. extname (filePath); switch (ext) {case ". html ": contentType =" text/html "; break; case ". js ": contentType =" text/javascript "; break; case ". css ": contentType =" text/css "; break; case ". gif ": contentType =" image/gif "; break; case ". jpg ": contentType =" image/jpeg "; break; case ". png ": contentType =" image/png "; break; case ". ico ": contentType =" image/icon "; break; default: contentType =" application/octet-stream ";} return contentType; // return content type string} // The main function of the Web server, parses the request, and returns the Web content var funWebSvr = function (req, res) {var reqUrl = req. url; // obtain the requested url // output the requested url to the console. log (reqUrl); // use the url parsing module to obtain the path name var pathName = libUrl in the url. parse (reqUrl ). pathname; if (libPath. extname (pathName) = "") {// if the path does not have the extension pathName + = "/"; // specify the Access Directory} if (pathName. charAt (pathName. length-1) = "/") {// If you access the directory pathName + = "index.html"; // specify as the default webpage} // use the path parsing module, assemble the actual file path var filePath = libPath. join (". /WebRoot ", pathName); // determines whether the file contains libPath. exists (filePath, function (exists) {if (exists) {// file exists // write content type res in the return header. writeHead (200, {"Content-Type": funGetContentType (filePath)}); // create a read-only stream to return var stream = libFs. createReadStream (filePath, {flags: "r", encoding: null}); // specifies that if the stream reading error occurs, the system returns the 404 error stream. on ("error", function () {res. writehead( 404); res. end ("404 Read Error") ;}); // connects the file stream and the http returned stream pipeline to return the actual Web content stream. pipe (res);} else {// the file does not exist // Error 404 res is returned. writehead( 404, {"Content-Type": "text/html"}); res. end ("404 Not Found") ;}}) ;}// create an http server var webSvr = libHttp. createServer (funWebSvr); // specify the Server Error Event Response webSvr. on ("error", function (error) {console. log (error); // output error information in the console}); // start listening for port 8124 webSvr. listen (8124, function () {// output the service startup information console to the console. log ('[WebSvr] [Start] running http://127.0.0.1:8124/ '); // End the Service Startup timer and output console. timeEnd (' [WebSvr] [Start] ');});

2. Resource Directory

To create a Web server, we need to create a WebRoot directory to store actual webpage and image resources. The "WebRoot" directory name is used in the above source code to assemble the actual file path.

Postscript

With Node. js, we can easily establish a relatively independent Web server. Its event-driven feature avoids tedious thread protection, and its basic module reduces development difficulty. The Web server created in this chapter is just a simple sample and does not consider many issues such as modularity and security. However, you can master some basic knowledge about Node. js development.

For more articles about how to create a simple Web server using Node. js, refer to the PHP Chinese website!

Related Article

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.