Home > Web Front-end > JS Tutorial > Node.js practice building a simple web server

Node.js practice building a simple web server

高洛峰
Release: 2016-12-28 11:24:02
Original
994 people have browsed it

If you are familiar with web development on .NET or other similar platforms, you may be like, what is the point of setting up a web server? Create a web project in Visual Studio and click to run. This is indeed the case, but please don't forget that the cost is that, for example, if you use .NET to develop a Web application, you use a complete IIS as your Web server foundation, so that when your application is released, it will I can only use IIS. And if you use a stand-alone server (built by yourself using System.Web.Hosting), you have to deal with various HttpListeners and corresponding threads, which will be more troublesome. After all, .NET is not focused on the Web. Node.js provides a convenient and customizable approach in this regard, on which you can build a sophisticated service platform that is fully oriented to your application.


1. Establishing 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 them in detail in future chapters), such as http, url, etc. Modules encapsulate specific functions and provide corresponding methods or properties. To use these modules, you need to first request the module to obtain its operation object.

For example, if you want to use the system's http module, you can write:

var libHttp = require('http'); //请求HTTP协议模块
Copy after login

In this way, future programs will be able to access the functions of the http module through the variable libHttp. The following system modules are used in the routines in this chapter:
http: encapsulates the server and client implementation of the http protocol;
url: encapsulates the parsing and processing of urls;
fs: encapsulates the function of file system operations ;
path: Encapsulates the path parsing function.
With these modules, we can build our own applications standing on the shoulders of giants.
2. Console
In order to better observe the running of the program and to check errors when exceptions occur, you can use the console function by passing the variable console.

console.log('这是一段日志信息'); 
计时并在控制台上输出计时信息: 
//开始计时 
console.timeEnd('计时器1'); //开始名称为“计时器1”的计时器 
... 
... 
... 
//结束计时,并输出到控制台 
console.timeEnd('计时器1'); //结束称为“计时器1”的计时器并输出
Copy after login

3. Define functions
The way to define functions in Node.js is exactly the same as in ordinary JavaScript, but our recommended writing method is as follows, that is, using a variable to name the function, which can be more convenient and clear Pass functions as parameters to other functions:

//定义一个名为showErr的函数 
var showErr=function(msg){ 
var inf="错误!"+msg; 
console.log(inf+msg); 
return msg; 
}
Copy after login

4. Create a Web server and listen for access requests
The most important thing about creating a Web server is to provide a response function for Web requests, 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. In the response function, the request information should be parsed, and the returned content should be assembled according to the request.

//请求模块 
var libHttp = require('http'); //HTTP协议模块 
//Web服务器主函数,解析请求,返回Web内容 
var funWebSvr = function (req, res){ 
res.writeHead(200, {'Content-Type': 'text/html'}); 
res.write(&#39;<html><body>&#39;); 
res.write(&#39;<h1>*** Node.js ***</h1>&#39;); 
res.write(&#39;<h2>Hello!</h2>&#39;); 
res.end(&#39;</body></html>&#39;); 
} 
//创建一个http服务器 
var webSvr=libHttp.createServer(funWebSvr); 
//开始侦听8124端口 
webSvr.listen(8124);
Copy after login

5. Parse Web requests
For simple Web page access requests, important information is contained in the URL of the request information parameters. We can use the URL parsing module to parse the access path in the URL and use The path module assembles the access path into the actual file path to be accessed for return.

var reqUrl=req.url; //获取请求的url 
//向控制台输出请求的路径 
console.log(reqUrl); 
//使用url解析模块获取url中的路径名 
var pathName = libUrl.parse(reqUrl).pathname; 
//使用path模块获取路径名中的扩展名 
if (libPath.extname(pathName)=="") { 
//如果路径没有扩展名 
pathName+="/"; //指定访问目录 
} 
if (pathName.charAt(pathName.length-1)=="/"){ 
//如果访问目录 
pathName+="index.html"; //指定为默认网页 
} 
//使用路径解析模块,组装实际文件路径 
var filePath = libPath.join("./WebRoot",pathName);
Copy after login

6. Set the return header
Since it is a Web request, the http return header needs to be included in the return content. The focus here is to set the content of the http return header according to the file extension of the file path to be accessed. type.

var contentType=""; 
//使用路径解析模块获取文件扩展名 
var ext=libPath.extname(filePath); 
switch(ext){ 
case ".html": 
contentType= "text/html"; 
break; 
case ".js": 
contentType="text/javascript"; 
break; 
... 
... 
default: 
contentType="application/octet-stream"; 
} 
//在返回头中写入内容类型 
res.writeHead(200, {"Content-Type": contentType });
Copy after login

7. Write the accessed file content into the returned object
With the actual path of the file that needs 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 returned to the client.

//判断文件是否存在 
libPath.exists(filePath,function(exists){ 
if(exists){//文件存在 
//在返回头中写入内容类型 
res.writeHead(200, {"Content-Type": funGetContentType(filePath) }); 
//创建只读流用于返回 
var stream = libFs.createReadStream(filePath, {flags : "r", encoding : null}); 
//指定如果流读取错误,返回404错误 
stream.on("error", function() { 
res.writeHead(404); 
res.end("<h1>404 Read Error</h1>"); 
}); 
//连接文件流和http返回流的管道,用于返回实际Web内容 
stream.pipe(res); 
} 
else { //文件不存在 
//返回404错误 
res.writeHead(404, {"Content-Type": "text/html"}); 
res.end("<h1>404 Not Found</h1>"); 
} 
});
Copy after login

2. Testing and operation
1. Complete source code
The following 100 lines of JavaScript are all the source code to create such a simple web server:

//------------------------------------------------ 
//WebSvr.js 
// 一个演示Web服务器 
//------------------------------------------------ 
//开始服务启动计时器 
console.time('[WebSvr][Start]'); 
//请求模块 
var libHttp = require('http'); //HTTP协议模块 
var libUrl=require('url'); //URL解析模块 
var libFs = require("fs"); //文件系统模块 
var libPath = require("path"); //路径解析模块 
//依据路径获取返回内容类型字符串,用于http返回头 
var funGetContentType=function(filePath){ 
var contentType=""; 
//使用路径解析模块获取文件扩展名 
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; //返回内容类型字符串 
} 
//Web服务器主函数,解析请求,返回Web内容 
var funWebSvr = function (req, res){ 
var reqUrl=req.url; //获取请求的url 
//向控制台输出请求的路径 
console.log(reqUrl); 
//使用url解析模块获取url中的路径名 
var pathName = libUrl.parse(reqUrl).pathname; 
if (libPath.extname(pathName)=="") { 
//如果路径没有扩展名 
pathName+="/"; //指定访问目录 
} 
if (pathName.charAt(pathName.length-1)=="/"){ 
//如果访问目录 
pathName+="index.html"; //指定为默认网页 
} 
//使用路径解析模块,组装实际文件路径 
var filePath = libPath.join("./WebRoot",pathName); 
//判断文件是否存在 
libPath.exists(filePath,function(exists){ 
if(exists){//文件存在 
//在返回头中写入内容类型 
res.writeHead(200, {"Content-Type": funGetContentType(filePath) }); 
//创建只读流用于返回 
var stream = libFs.createReadStream(filePath, {flags : "r", encoding : null}); 
//指定如果流读取错误,返回404错误 
stream.on("error", function() { 
res.writeHead(404); 
res.end("<h1>404 Read Error</h1>"); 
}); 
//连接文件流和http返回流的管道,用于返回实际Web内容 
stream.pipe(res); 
} 
else { //文件不存在 
//返回404错误 
res.writeHead(404, {"Content-Type": "text/html"}); 
res.end("<h1>404 Not Found</h1>"); 
} 
}); 
} 
//创建一个http服务器 
var webSvr=libHttp.createServer(funWebSvr); 
//指定服务器错误事件响应 
webSvr.on("error", function(error) { 
console.log(error); //在控制台中输出错误信息 
}); 
//开始侦听8124端口 
webSvr.listen(8124,function(){ 
//向控制台输出服务启动的信息 
console.log('[WebSvr][Start] running at http://127.0.0.1:8124/'); 
//结束服务启动计时器并输出 
console.timeEnd('[WebSvr][Start]'); 
});
Copy after login

2. Resource directory

Since we want to establish a Web server, we need to create a WebRoot directory to store actual web pages and image resources. The directory name of "WebRoot" is used in the above source code to assemble the actual file path.

Node.js实战 建立简单的Web服务器

3. Run and test

Enter in the command line:

node.exe WebSvr.js

Our Web server is now running. At this time, it can be accessed through the browser. The operation effect is as follows:

Node.js实战 建立简单的Web服务器

## Postscript

Using Node.js we can easily build a relatively independent web server. Its event-driven features avoid cumbersome thread protection, and its basic modules reduce the difficulty of development. The web server established in this chapter is just a simple sample, without too much consideration of modularity, security and other issues, but it can help you master some basic knowledge of Node.js development.

For more Node.js practical articles related to establishing a simple web server, please pay attention to the PHP Chinese website!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template