How to build a simple Web server with Node. js-js tutorial

Source: Internet
Author: User
In this chapter, we also use Node. js creates a simple Web server. in the previous chapter, we introduced Node. js, a JavaScript Server Platform for Internet services, and Node. the js runtime environment has been set up and verified by two HelloWorld programs. basic functions of js. In this chapter, we also use Node. js to build a simple Web server through practical drills.

If you are familiar with Web Development of. NET or other similar platforms, you may 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:

The Code is 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.

The Code is as follows:


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
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:

The Code is as follows:


// 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.

The Code is as follows:


// Request module
Var libHttp = require ('http'); // http protocol module
// The main function of the Web server, 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 on port 8124
WebSphere SVR. 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.

The Code is as follows:


Var reqUrl = req. url; // obtain the request url
// Output the Request Path to the console
Console. log (reqUrl );
// Use the url parsing module to obtain the path name in the url
Var pathName = libUrl. parse (reqUrl). pathname;
// Use the path module to obtain the extension in the path name
If (libPath. extname (pathName) = ""){
// If the path does not have an extension
PathName + = "/"; // specify the Access Directory
}
If (pathName. charAt (pathName. length-1) = "/"){
// If you access the Directory
PathName + = "index.html"; // specifies the default webpage
}
// Use the path parsing module to 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.

The Code is as follows:


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? 1.1.23 ":
ContentType = "text/javascript ";
Break;
...
...
Default:
ContentType = "application/octet-stream ";
}
// Write the content type in the return Header
Res. 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.

The Code is as follows:


// Determine whether a file exists
LibPath. exists (filePath, function (exists ){
If (exists) {// The object exists
// Write the content type in the return Header
Res. writeHead (200, {"Content-Type": funGetContentType (filePath )});
// Create a read-only stream for returning
Var stream = libFs. createReadStream (filePath, {flags: "r", encoding: null });
// If the stream reading error occurs, Error 404 is returned.
Stream. on ("error", function (){
Res. writeHead (404 );
Res. end ("404 Read Error ");
});
// Connect the file stream and the http return Stream pipeline to return the actual Web Content
Stream. pipe (res );
}
Else {// the file does not exist
// Error 404 is returned.
Res. 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:

The Code is as follows:


//------------------------------------------------
// WebSvr. js
// A demo Web Server
//------------------------------------------------
// Start the service Timer
Console. time ('[WebSvr] [Start]');
// Request module
Var libHttp = require ('http'); // http protocol module
Var libUrl = require ('url'); // url parsing module
Var libFs = require ("fs"); // File System Module
Var libPath = require ("path"); // path parsing module
// Obtain the string of the returned content type based on the path, used for the http return Header
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? 1.1.23 ":
ContentType = "text/javascript ";
Break;
Case ". css? 1.1.23 ":
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; // string of the returned content type
}
// 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 request url
// Output the Request Path to the console
Console. log (reqUrl );
// Use the url parsing module to obtain the path name in the url
Var pathName = libUrl. parse (reqUrl). pathname;
If (libPath. extname (pathName) = ""){
// If the path does not have an extension
PathName + = "/"; // specify the Access Directory
}
If (pathName. charAt (pathName. length-1) = "/"){
// If you access the Directory
PathName + = "index.html"; // specifies the default webpage
}
// Use the path parsing module to assemble the actual file path
Var filePath = libPath. join ("./WebRoot", pathName );
// Determine whether a file exists
LibPath. exists (filePath, function (exists ){
If (exists) {// The object exists
// Write the content type in the return Header
Res. writeHead (200, {"Content-Type": funGetContentType (filePath )});
// Create a read-only stream for returning
Var stream = libFs. createReadStream (filePath, {flags: "r", encoding: null });
// If the stream reading error occurs, Error 404 is returned.
Stream. on ("error", function (){
Res. writeHead (404 );
Res. end ("404 Read Error ");
});
// Connect the file stream and the http return Stream pipeline to return the actual Web Content
Stream. pipe (res );
}
Else {// the file does not exist
// Error 404 is returned.
Res. 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 on the console
});
// Start listening on port 8124
WebSvr. listen (8124, function (){
// Output the service startup information to the console
Console. log ('[WebSvr] [Start] running at 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.

3. Run and Test

Enter:

node.exe WebSvr.js

Our Web server is running, and you can access it through a browser. The running effect is as follows:

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.
Author: Wang Feng www.otlive.cn

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.