Use node. js to implement simple web Servers

Source: Internet
Author: User
Nodejs is still relatively simple to implement web servers. I understand that nodejs started with "node entry". If you do not know nodejs, you can check it out! I completed step-by-step exercises based on the book, and I did know about nodejs. However, it is inconvenient to write routes in the book, with 10 nodes. js web server implementation is relatively simple. I understand node. js started with node entry. If you do not know about node. js can also be viewed! I completed step-by-step exercises based on the book, and I did know about node. js. However, it is inconvenient to write routes in it. On the last day of the 11th holiday, I tried to write a simple web server. Now I share the record here! The http module provides basic functions, So I mainly solve two problems: Processing static resources and routing dynamic resources. Static resources in node. js do not change, such as slices, front-end js, css, and html pages. Dynamic resources generally refer to aspx pages, ashx pages, asp pages, jsp pages, php pages, and node. in js, there is actually no dynamic resource. The callback method is used to process the request. In my httserver implementation, I used the ashx method as a reference, regard the js file that processes the request as a dynamic resource. First, implement a function to process static resources, which is actually to read local files. This method can meet the processing requirements of static resources mentioned above. // Process static resource function staticResHandler (localPath, ext, response) {fs. readFile (localPath, "binary", function (error, file) {if (error) {response. writeHead (500, {"Content-Type": "text/plain"}); response. end ("Server Error:" + error);} else {response. writeHead (200, {"Content-Type": getContentTypeByExt (ext)}); response. end (file, "binary") ;}});} dynamic resources cannot be done in one way, just as your website has register. aspx, login. aspx and so on, all need You can write it by yourself. In my httpserver, each js module that processes the request exports processRequest (request, response). For example, you can implement a register. js (only output string register) exports. processRequest = function (request, response) {response. writeHead (200, {'content-type': 'text/plain '}); resp. end ("register");} when the request arrives, we need to decide how to handle it, that is, the route. Because static resource URLs are used to specifying static resources, they will not change here, for example, accessing http://localhost/img/logo.png Access the web root directory \ img \ logo.png; Access http://localhost/js/what.js Access the web root directory \ js \ what. js. Dynamic resources are also common js files, that is, server-side js. For example, I implemented this httpserver. js and the above-mentioned register. js should not be accessed by users, so it should be judged during routing, that is, some if and else. Simple and powerful are my favorites. Here we only look at the final judgment, fs. exists (localPath, function (exists) {if (staticRes) {staticResHandler (localPath, ext, response); // static resource} else {try { Var handler = require (localPath );If (handler. processRequest & typeof handler. processRequest = 'function '){ Handler. processRequest (request, response );// Dynamic resource} else {response. writeHead (404, {'content-type': 'text/plain '}); response. end ('1970: Handle Not found ');} catch (exception) {console. log ('error: url: '+ request. url + 'msg: '+ exception); response. writeHead (500, {"Content-Type": "text/plain"}); response. end ("Server Error:" + exception) ;}} else {// the resource does not exist response. writeHead (404, {'content-type': 'text/plain '}); response. end ('1970: File Not found ') ;}}); process static resources as mentioned above. Please refer to the two sentences for Processing dynamic resources, localPath is the backend js path relative to the web root directory. js is in the root directory/src/account folder, then your url request is http://localhost/account/register At this time, localPath is./src/account/register. js. Note that this is not MVC, but the url does not have the src path and. js suffix. Why? It is to be separated from the front-end js file! In addition, a program without configuration is not a good program, but my configuration is always bad! (You may feel like I am writing a mess, but it doesn't matter. The complete code will be provided later. Let's take a look at it. If you feel good, you have downloaded the example and run it on your computer, I am also very honored !) // Configure var config = {port: 80, denyAccess :['. /httpserver. js ','. /src/requirecache. js'], localIPs: ['127. 0.0.1 '], srcpath:'/src '};. /src/requirecache. what is the js file? Here we need to explain that the require method has a caching mechanism, which caches all loaded modules to require. in the cache object, when the second request is sent, the cache module is directly returned. Of course, this is for performance consideration, but I will modify the register. js does not want to restart the web server. If it doesn't matter, this special dynamic resource is not needed. Please understand, requirecache. js and register. js is the same as js files that process requests. Requirecache. the function of the js module is to delete the template cache: var querystring = require ('querystring'); var url = require ('url'); exports. processRequest = function (request, response) {response. writeHead (200, {'content-type': 'text/html'}); var qs = querystring. parse (url. parse (request. url ). query); if (qs. key) {delete require. cache [qs. key];} response. write (''); For (var key in require. cache) {response. write (''+ key +'
');} Response. write ('view
'); Response. end ('');}

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.