Implementation of routing function in Nodejs _node.js

Source: Internet
Author: User

Learning node, you found a completely different view of your previous views-what is the JavaScript in your eyes, and what is it for? Effects? Or is it just an interaction with the client? It can be said that JavaScript is the first to run in the browser, however, you want to think that the browser is just you provide a context, it defines what to use JavaScript can do, here you can think of a similar enterprise, the enterprise defines what you can do here, But it doesn't say much about what the JavaScript language itself can do. In fact, as a complete language, JavaScript can be used in different contexts to reflect different abilities. The Nodejs mentioned here is actually a context, a running environment that allows JavaScript code to run on the back end (out of the browser environment).

The core of routing is routing, as the name suggests, routing means that we have different ways of dealing with different URLs, such as dealing with/start business logic and handling the business of/upload modules; logic is inconsistent. In reality, the routing process "ends" in the routing module, and the routing module is not really a "take action" module for the request, or it will not be well extended when our application becomes more complex.

Here we first create a module called Requesthandlers, which adds a placeholder function for each request handler:


Copy Code code as follows:

function Start () {
Console.log ("Request handler ' start ' was called.");

function sleep (milliseconds) {
var starttime=new Date (). GetTime ();
while (new Date (). GetTime () <starttime+milliseconds);
}
Sleep (10000);
Return "Hello Start";
}
function upload () {
Console.log ("Request handler ' upload ' was called.");
Return "Hello Upload";
}

Exports.start=start;
Exports.upload=upload;

This allows us to connect the request handler with the routing module, giving way to "a path to follow". Then we decided to pass a series of request handlers through an object, and we needed to inject this object into the router () function in a loosely coupled way, and the main file index.js:


Copy Code code as follows:

var server=require ("./server");
var router=require ("./router");
var requesthandlers=require ("./requesthandlers");

var handle={};
handle["/"]=requesthandlers.start;
handle["/start"]=requesthandlers.start;
handle["/upload"]=requesthandlers.upload;

Server.start (Router.route,handle);

As shown above, it is easy to map different URLs to the same request handler: Just add a property with a key to "/" in the object, corresponding to the Requesthandlers.start. This allows us to simply configure/start and/requests to be processed by the start handler. After we have finished looking at the definition of the object, we pass it as an additional parameter to the server, see Server.js:

Copy Code code as follows:

var http=require ("http");  
var url=require ("url");  & nbsp
 
Function Start (route,handle) {  
    function onrequest (request,response ) {  
        var pathname=url.parse (request.url) .pathname;   
        console.log ("Request for" +pathname+ "received.");   
          
         Route (handle,pathname);  
           
        response.writehead (200,{"Content-type": "Text/plain"});   
        var content=route (handle,pathname);  
& nbsp;       Response.Write (content);   
        response.end ();  
   }   
    http.createserver (onrequest) Listen (8888);  
    Console.log ("Server has started.");   
}   
Exports.start=start;

This adds the handle parameter to the start () function and passes the handle object as the first argument to the route () callback function, which defines route.js:

Copy Code code as follows:

Function route (handle,pathname) {
Console.log ("About to route a request for" + pathname);
if (typeof handle[pathname]=== ' function ') {
return Handle[pathname] ();
}else{
Console.log ("No request handler found for" +pathname);
Return "404 Not Found";
}
}
Exports.route=route;

With the above code, we first check whether the request handler for the given path exists, and call the corresponding function directly if it exists. We can get the request processing function from the passed object in the same way as the element in the associative array, that is, Handle[pathname] (); Such an expression, giving a feeling is like saying "Hey, please help me with this path." "The program works as shown below:

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.