This is a simple node app with routing. Code follows :
var http = require("http");
var url = require("url");
var route = {
routes:{},
for:function(path, handler){
console.log("route path = "+path);
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'){
console.log(" main pathname = "+pathname);
route.routes[pathname](request, response);
}else{
response.writeHead(404, {"Content-Type": "text/plain"});
response.end("404 Not Found");
}
}// END OF ONrEQUEST
http.createServer(onRequest).listen(9999);
console.log("Server has started at 9999.");
When I run the app I see in console:
route path = /start
route path = /finish
Server has started at 9999.
When I hit at http://localhost:9999/finish, I find in console :
Request for /finish received.
main pathname = /finish
I am trying to understand the code- at first the route
object variable is constructed.
Q1) How does the for
property work there ?
Let us look at the following line :
route.for("/start", function(request, response){
It seems to be related with the for
property in whatever ways.
Q2) How is it related with the for
property ?
via Istiaque Ahmed
No comments:
Post a Comment