This article mainly introduces how to build a Web server for Nodejs. In this article, we will use Nodejs to build a simple Web server. If you are interested, refer to building a Web server using Nodejs to learn Node. js is a comprehensive introductory tutorial. To complete a simple Web server, you need to learn several important modules in Nodejs, such: the http protocol module, file system, url parsing module, path parsing module, and 301 redirection problems. Next we will briefly explain how to build a simple Web server.
As a Web server, you must have the following functions:
1 Tib displays Web pages ending with .html/. htm
2. You can directly open the file content ending with. js/. css/. json/. text.
3. display image resources
4、automatically downloads files ending with .apk/. docx/. zip
5, such as http://xxx.com/a/ B/, then find the directory B contains index.html, if there is show, if not, list all the files and folders under the directory, and further access.
6, such as http://xxx.com/a/ B, 301 redirection to the http://xxx.com/a/ B/, this can solve the internal resource reference dislocation problem.
Introduce the following modules:
// Http module var http = require ('http'); // url parsing module var url = require ('url '); // file system module var fs = require ("fs"); // path parsing module var path = require ("path ");
Create a service and listen on the specified port:
// Create a service var httpServer = http. createServer (this. processRequest. bind (this); // listen to the service httpServer on the specified port. listen (port, function () {console. log ("[HttpServer] [Start]", "runing at http: //" + ip + ":" + port + "/"); console. timeEnd ("[HttpServer] [Start]") ;});
When creating a service, you must pass an anonymous function processRequest to process the request. processRequest receives two parameters: request and response. The request object contains all the content of the request, request is used to set the response header and respond to the client.
ProcessRequest: function (request, response) {var hasExt = true; var requestUrl = request. url; var pathName = url. parse (requestUrl ). pathname; // decodes the Request path to prevent Chinese garbled pathName = decodeURI (pathName); // if the path does not have an extension if (path. extname (pathName) = '') {// if it does not end with a slash (/), add the slash (/) and perform 301 redirection if (pathName. charAt (pathName. length-1 )! = "/") {PathName + = "/"; var redirect = "http: //" + request. headers. host + pathName; response. writeHead (301, {location: redirect}); response. end () ;}// Add the default access page, but this page does not necessarily exist. pathName + = "index.html"; hasExt = false; // mark the default page as automatically added by the program} // obtain the relative path of the resource file var filePath = path. join ("http/webroot", pathName); // obtain the file type var contentType = this. getContentType (filePath); // if the file name exists fs. exists (filePath, function (exists) {if (exists) {response. writehead( 200, {"content-type": contentType}); var stream = fs. createReadStream (filePath, {flags: "r", encoding: null}); stream. on ("error", function () {response. writeHead (500, {"content-type": "text/html"}); response. end ("500 Server Error") ;}); // returns the file content stream. pipe (response);} else {// if (hasExt) {// if this file is not automatically added by the program, the system returns 404 response. writeHead (404, {"content-type": "text/html"}); response. end ("404 Not Found");} else {// if the file is automatically added by the program and does Not exist, indicates that the user wants to access the file list var html ="
"; Try {// User Access Directory var filedir = filePath. substring (0, filePath. lastIndexOf ('\'); // obtain the file list in the user access path var files = fs. readdirSync (filedir); // list all files in the access path and add hyperlinks so that you can further access for (var I in files) {var filename = files [I]; html + =""+ Filename +"
";}} Catch (e) {html + =" the directory you accessed does not exist "} response. writeHead (200, {"content-type": "text/html"}); response. end (html );}}});},
There are several key points in the request processing function:
If the path contains Chinese characters, the browser will automatically encode the code (English remains unchanged, and Chinese characters will change). Therefore, after receiving the address, you need to decode the address, otherwise, the obtained path does not match the actual path,
When the access path does not end with a specific file and does not end with a slash (/), add a slash (/) to indicate the current directory. Otherwise, the static resources in the current path cannot be found.
If the access path is a directory, all files and folders under the directory are listed, and you can click access. To make the Chinese directory display properly, set charset = UTF-8 in the header.
The core code is so much, around 140 lines, the complete code has been uploaded to Git: https://github.com/git-onepixel/Node
To run the demo, open cmd to switch to the root directory and run node start.
The above is all the content of this article, hoping to help you learn.