Node.js to build a simple Web server _javascript skills

Source: Internet
Author: User
In the previous chapter, we introduced the Node.js Web service-oriented JavaScript server platform, while Node.js's operating environment has been set up, and through two HelloWorld programs to verify the basic functions of node.js. In this chapter we also use Node.js to build a simple Web server.

If you are familiar with. NET or other similar platform for web development, you might like to build a Web server with what, create a Web project in Visual Studio, click Run. It is indeed true, but please do not forget that the price is more than if you are using. NET development Web application, you use the complete IIS as your Web server foundation, so that when your application is published, you can use IIS only. And if you use a standalone server (built using System.Web.Hosting yourself), you have to deal with various httplistener and corresponding threads, which can be tricky, after all. NET is not focused on Web-oriented. Node.js provides a convenient and customizable way to build a service platform that is sophisticated and fully geared to your application.


first, the establishment of a simple Web server involves node.js some basic knowledge points:

1. Request Module
In Node.js, the system provides a number of useful modules (you can also use JavaScript to write your own modules, which we will explain in detail later), such as HTTP, URLs, and so on. The module encapsulates a specific function that provides the appropriate method or attribute to use, and the module needs to be requested to obtain its operating object first.

For example, to use the system's HTTP module, you can write this:

Copy Code code as follows:

var libhttp = require (' http '); Request HTTP Protocol Module

In this way, future programs will be able to access the HTTP module functionality through variable libhttp. The following system modules are used in this chapter routines:
http: Encapsulates the HTTP protocol server and client implementation;
URL: Encapsulates the parsing and processing of URLs;
FS: Encapsulates the function of the file system operation;
Path: Encapsulates the parsing function for a path.
With these modules, we can stand on the shoulders of giants to build their own applications.
2. Control Station
In order to better observe the operation of the program, convenient in the exception to see the error, you can laxative variable console using the function of the console.
Copy Code code as follows:

Console.log (' This is a log message ');
Timing and output timing information on the console:
Start the timer.
Console.timeend (' timer 1 '); Timer with start name "Timer 1"
...
...
...
End timings and output to console
Console.timeend (' timer 1 '); Ends the timer called "Timer 1" and outputs

3. Defining functions
The method of defining functions in Node.js is exactly the same as in normal JavaScript, but we recommend the following, even if a variable is used to name a function, it is easier to explicitly pass a function as an argument to another function:
Copy Code code as follows:

To 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 a response function for the Web request, which has two parameters, the first one represents the client-requested information, and the other represents the information that will be returned to the client. The request information should be resolved in the response function, and the back content should be assembled according to the request.
Copy Code code as follows:

Request Module
var libhttp = require (' http '); HTTP Protocol Module
Web server main function, parse request, return Web content
var funwebsvr = function (req, res) {
Res.writehead ({' Content-type ': ' text/html '});
Res.write (' Res.write (' Res.write (' Res.end (' </body>}
Create an HTTP Server
var websvr=libhttp.createserver (FUNWEBSVR);
Start listening on port 8124
Websvr.listen (8124);

5. Parse Web Requests
For a simple Web page access request, the important information is contained in the URL of the request information parameter, we can use the URL parsing module to resolve the access path in the URL, and use the path module to assemble the access path to the actual file path to be accessed for return.
Copy Code code as follows:

var Requrl=req.url; Get the requested URL
To output the requested path to the console
Console.log (Requrl);
Using the URL resolution module to get the path name in the URL
var pathName = Liburl.parse (requrl). PathName;
Use the path module to get the extension in the path name
if (Libpath.extname (pathName) = = "") {
If the path does not have an extension
pathname+= "/"; Specify Access Directory
}
if (Pathname.charat (pathname.length-1) = = "/") {
If you access the directory
pathname+= "index.html"; Specify as Default page
}
Assemble the actual file path using the path resolution module
var FilePath = Libpath.join ("./webroot", pathName);

6. Set Return header
Because it is a Web request, you need to include the HTTP return header in the return content, which focuses on setting the content type of the HTTP return header based on the file name extension of the file path that you want to access.
Copy Code code as follows:

var contenttype= "";
Using the path resolution module to get the file name 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";
}
Writing the content type in the return header
Res.writehead ({"Content-type": ContentType});

7, write access to the returned object to the contents of the file
With the actual path of the file that needs to be accessed, with the corresponding content type of the file, you can use the FS file system module to read the file stream and return it to the client.
Copy Code code as follows:

To determine whether a file exists
Libpath.exists (Filepath,function (exists) {
if (exists) {//File exists
Writing the content type in the return header
Res.writehead ({"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 reads incorrectly, a 404 error is returned
Stream.on ("Error", function () {
Res.writehead (404);
Res.end ("});
A conduit for connecting file streams and HTTP return streams to return actual web content
Stream.pipe (RES);
}
else {//file does not exist
Return 404 error
Res.writehead (404, {"Content-type": "Text/html"});
Res.end ("}
});

Second, testing and operation
1. Complete source code
The following 100 lines of JavaScript are all the source code to build such a simple Web server:
Copy Code code as follows:

//------------------------------------------------
Websvr.js
A demo Web server
//------------------------------------------------
Start the service start 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 Resolution Module
Gets the return content type string based on the path used for the HTTP return header
var fungetcontenttype=function (FilePath) {
var contenttype= "";
Using the path resolution module to get the file name 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; Returns the content type string
}
Web server main function, parse request, return Web content
var funwebsvr = function (req, res) {
var Requrl=req.url; Get the requested URL
To output the requested path to the console
Console.log (Requrl);
Using the URL resolution module to get 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 Access Directory
}
if (Pathname.charat (pathname.length-1) = = "/") {
If you access the directory
pathname+= "index.html"; Specify as Default page
}
Assemble the actual file path using the path resolution module
var FilePath = Libpath.join ("./webroot", pathName);
To determine whether a file exists
Libpath.exists (Filepath,function (exists) {
if (exists) {//File exists
Writing the content type in the return header
Res.writehead ({"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 reads incorrectly, a 404 error is returned
Stream.on ("Error", function () {
Res.writehead (404);
Res.end ("});
A conduit for connecting file streams and HTTP return streams to return actual web content
Stream.pipe (RES);
}
else {//file does not exist
Return 404 error
Res.writehead (404, {"Content-type": "Text/html"});
Res.end ("}
});
}
Create an HTTP Server
var websvr=libhttp.createserver (FUNWEBSVR);
Specify server Error Event response
Websvr.on ("Error", function (Error) {
Console.log (Error); outputting error messages in the console
});
Start listening on port 8124
Websvr.listen (8124,function () {
Output service startup information to the console
Console.log (' [Websvr][start] running at http://127.0.0.1:8124/');
End service start Timer and output
Console.timeend (' [Websvr][start] ');
});

2. Resource Catalogue

Now that you want to build a Web server, we need to create a WebRoot directory to store the actual page and picture resources, "WebRoot" directory name in the above source code is used to assemble the actual file path.

3. Run and test

On the command line, enter:

Node.exe Websvr.js

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

Postscript

    Using node.js, we can facilitate the establishment of relatively independent Web servers, its event-driven features to avoid cumbersome thread protection, the basic module to reduce the difficulty of development. The Web server set up in this chapter is just a simple sample, not too much consideration of modularity, security and other issues, but can grasp the node.js development of some basic knowledge.
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.