first, establishing a simple Web server involves some basic points of node. JS:
1. Request Module
In node. JS, the system provides a number of useful modules (you can, of course, write your own modules in JavaScript, which we'll explain in detail later), such as HTTP, URLs, and so on. Modules encapsulate specific functions, provide the appropriate methods or properties, and to use these modules, you need to request the module to get its operands first.
For example, to use the system's HTTP module, you can write:
var libhttp = require (' http '); Request HTTP Protocol Module
In this way, future programs will be able to access the functionality of the HTTP module through the variable libhttp. The following system modules are used in this chapter's routines:
http: Server and client implementations that encapsulate the HTTP protocol;
URL: Encapsulates the parsing and processing of URLs;
FS: Encapsulates the functionality of file system operations;
Path: Encapsulates the parsing capabilities of the path.
With these modules, we can stand on the shoulders of giants and build our own applications.
2. Control Station
In order to better observe the operation of the program, easy to view errors in the exception, you can defecate variable console using the function of the console.
Timing and output timing information on the console:
Start timing
Console.timeend (' timer 1 '); Start timer with Name "Timer 1"
...
...
...
End timing and output to console
Console.timeend (' timer 1 '); Ends a timer called Timer 1 and outputs
3. Defining functions
Defining a function in node. JS is exactly the same as in normal JavaScript, but we recommend the following, even if you use a variable to name a function, which makes it easier to explicitly pass the function as an argument to another function:
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 represents the information requested by the client, and the other represents the information that will be returned to the client. The request information should be parsed in the response function, and the back content should be assembled according to the request.
Request Module
var libhttp = require (' http '); HTTP Protocol Module
Web server main function, parsing requests, returning Web content
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
5. Parsing Web Requests
For simple Web page access requests, important information is included in the URL of the request information parameters, we can use the URL parsing module to resolve the URL of the access path, and the path module, the access path is assembled to the actual file path to be accessed for return.
var Requrl=req.url; Gets the requested URL
To output the requested path to the console
Console.log (Requrl);
Get the path name in the URL using the URL resolution module
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 a name extension
pathname+= "/"; Specify access to Directory
}
if (Pathname.charat (pathname.length-1) = = "/") {
If you access the directory
pathname+= "index.html"; Specify as Default Web page
}
Assemble the actual file path using the path resolution module
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, which focuses on setting the content type of the HTTP return header based on the file name extension of the file path to be accessed.
var contenttype= "";
Get the file name extension using the path resolution module
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 content types in the return header
Res.writehead ($, {"Content-type": ContentType});
7. Write the contents of the accessed file to the returned object
With the actual path of the file that needs to be accessed, the file stream can be read and returned to the client by using the FS file system module, with the content type corresponding to the files.
Libpath.exists (Filepath,function (exists) {
if (exists) {//File exists
Writing content types 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 a 404 error is returned if the stream reads an error
A pipeline that connects file streams and HTTP return streams for returning actual web content
Stream.pipe (RES);
else {//file does not exist
404 Error returned
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 for building such a simple Web server:
1//------------------------------------------------
2//websvr.js
3//A demo Web server
4//------------------------------------------------
5
6//Start service start timer
7 Console.time (' [Websvr][start] ');
8
9//Request Module
Ten var libhttp = require (' http '); HTTP Protocol Module
One-to-one var liburl=require (' url '); URL Parsing module
var Libfs = require ("FS"); File System Module
var LibPath = require ("path"); Path parsing module
14
15//Based on path gets the return content type string for the HTTP return header
var fungetcontenttype=function (FilePath) {
* var contenttype= "";
18
19//Use the path resolution module to get the file name extension
var ext=libpath.extname (FilePath);
21st
Switch (EXT) {
". html":
Contenttype= "text/html";
break;
". js":
Contenttype= "Text/javascript";
break;
Case ". css":
Contenttype= "Text/css";
break;
Case ". gif":
Contenttype= "Image/gif";
a break;
". jpg":
Contenttype= "Image/jpeg";
PNS break;
". png":
Contenttype= "Image/png";
a break;
". ico":
Contenttype= "Image/icon";
break;
Default:
Contenttype= "Application/octet-stream";
46}
47
ContentType return; Returns the content type string
49}
50
//web Server main function, parse request, return Web content
Funwebsvr var = function (req, res) {
var Requrl=req.url; Gets the requested URL
54
55//Output The requested path to the console
Console.log (Requrl);
57
58//Use URL parsing module to get the path name in the URL
pathName var = liburl.parse (Requrl). PathName;
60
if (Libpath.extname (pathName) = = "") {
62//If path does not have extension
pathname+= "/"; Specify access to Directory
64}
65
if (Pathname.charat (pathname.length-1) = = "/") {
67//If you access the directory
pathname+= "index.html"; Specify as Default Web page
69}
70
71//Use Path resolution module to assemble the actual file path
FilePath var = libpath.join ("./webroot", pathName);
73
74//Determine if the file exists
Libpath.exists (Filepath,function (exists) {
if (exists) {//File exists
77//write the content type in the return header
Res.writehead ($, {"Content-type": Fungetcontenttype (FilePath)});
79
80//Create read-only stream for return
Bayi var stream = Libfs.createreadstream (FilePath, {flags: "R", Encoding:null});
82
83//Specify 404 error if stream read error
Stream.on ("Error", function () {
Res.writehead (404);
Res.end ("87});
88
89//Connect file stream and HTTP return stream for the pipeline to return the actual web content
Stream.pipe (RES);
91}
A. else {//file does not exist
93
94//Return 404 error
Res.writehead (404, {"Content-type": "Text/html"});
Res.end ("97}
98});
99
100
101
102}
103
104//Create an HTTP server
Websvr=libhttp.createserver var (funwebsvr);
106
107//Specify Server Error Event response
108 Websvr.on ("Error", function (Error) {
109 Console.log (Error); Output error message in console
110});
111
112
113//Start listening on 8124 ports
Websvr.listen (8124,function () {
115
116//To the console output service startup information
117 Console.log (' [Websvr][start] running at http://127.0.0.1:8124/');
118
119//End service start timer and output
Console.timeend (' [Websvr][start] ');
Learn to build a simple Web server with node. js