0

I understand the basics of routing in Node.js and using the http module for it. I understand all the Node.js code below but just the JavaScript API part and how it is used to make the routing code much more cleaner is what I have trouble understanding. When I say "trouble understanding" I mean trouble understanding the syntax and how the routes object is used.

The code is from an E-book I have been learning from so please read the code below.

var http = require("http"); 
var url = require("url");

var route = {   
  routes : {},
  for: function(path, handler){    
    this.routes[path] = handler;  
  } 
};

route.for("/start", function(request, response){    
  response.writeHead(200, {"Content-Type": "text/plain"});    
  response.write("Hello");    response.end();  
});

  route.for("/finish", function(request, response){    
    response.writeHead(200, {"Content-Type": "text/plain"});    
    response.write("Goodbye");   
    response.end();  
  });

function onRequest(request, response) {  
  var pathname = url.parse(request.url).pathname;  
  console.log("Request for " + pathname + " received.");  
  if(typeof route.routes[pathname] ==='function'){    
    route.routes[pathname](request, response);  
  }else{    
    response.writeHead(404, {"Content-Type": "text/plain"});    
    response.end("404 Not Found");  
  } 
}

http.createServer(onRequest).listen(9999); 
console.log("Server has started.")

My understanding so far is that: route.routes is an empty object and route.for is a function. The function has two parameters function(path,handler) but I don't understand the part in the function i.e. this.routes[path] = handler;

From my understanding this.routes[path] is an empty object so is the code setting handler to an empty object?

and beyond this I have absolutely no clue what function onRequest(request,response){}; is doing.

Plase explain the whole code for me as I find it very disturbing not being able to understanding the basics before progressing through the E-book.

lalitpatadiya
  • 720
  • 7
  • 21
LinDan ChongWei
  • 193
  • 3
  • 15
  • When `this.routes` is an empty object, assigning to `this.routes[path]` will **create a property**! – Bergi Jun 05 '15 at 02:56
  • `onRequest` is passed to the `http.createServer(…)` call. Didn't you say you understood the `http` module? – Bergi Jun 05 '15 at 02:58
  • I don't understand the actual function though. for example ` if(typeof route.routes[pathname] ==='function'){ route.routes[pathname](request, response); ` – LinDan ChongWei Jun 05 '15 at 03:41
  • That's simply "if there is a property with the name `pathname` in `route.routes` that has a function for its value, call that". Quite literally. – Bergi Jun 05 '15 at 04:06
  • @Bergi But thus it is impossible to gain access to the property of an object `route.routes[pathname]`, is not it? So If I do http://pastebin.com/2qCqWucH its will not work. But why this `route.routes[pathname]` working ? – shell_bug Apr 10 '16 at 21:45
  • @Zadohlik: I didn't really get your question, but it seems you are confused about [dot vs bracket notation](http://stackoverflow.com/q/4968406/1048572) – Bergi Apr 10 '16 at 21:48
  • @Bergi I mean I do not understand why this `typeof route.routes[pathname]` is equal to `'function'` (in code of question on line 24). How to get the name of this function, or to see how it looks ? This problem is confused for me and I not want to create duplicate of question and ask it here, in comments. – shell_bug Apr 11 '16 at 09:36
  • @Zadohlik: Just drop the `typeof` operator and you'll get the function object. The function doesn't necessarily have a name, you can see it's definition in the respective `route.for(…)` call – Bergi Apr 11 '16 at 10:34
  • I have the same question as LinDan. After reading the responses, none have satisfactorily answered his question. What does the following snippet do in the code of lines 4-9 given by him above? *** var route = { routes : {}, for: function(path, handler){ this.routes[path] = handler; } }; *** – thad Oct 19 '17 at 17:01

1 Answers1

1

Http module that you include in first line has createserver function that takes a function as a parameter. In of the last lines we pass "onRequest" function to it. The function passed is internally invoked by http module whenever request is recived on port 9999 as also defined. Function onRequest is invoked with two parameters one is "request" that contains data like headers and body of a request that was recived. 2nd parameter is respons object it is whats sent back. It has functions that facilate this like writeHead which writes headers, .end which signals http module to sned the response finally back.

onRequest function can do whatever it wants with the request and send whatever response it wants to send back.

Here it using url module that is native to nodejs parses url and extract pathname which is everything after first / so www.mydomain.com/thispart/andthis...etc are extracted.

Then thus is done to do object lookup inside the routes. If object with key that is equal to string of this pathname exists it will return the value that is the function and if not the expression will evaluate to false and 404 part will be run. Upon match function gets invoked with response and request objects that onRequest got in the parameters.

In Javascript property of an object can be set even if its not present..

var a = {n:1};
a.x = "exists";
console.log (a.x); //exists
Muhammad Umer
  • 17,263
  • 19
  • 97
  • 168