
路由选择的核心是路由,顾名思义,路由指的就是我们要针对不同的URL有不同的处理方式,例如处理/start的业务逻辑和处理/upload模块 的业务;逻辑就是不一致的。在现实的实现下,路由过程会在路由模块中“结束”,并且路由模块并不是真正者针对请求“采取行动”的模块,否则当我们的应用程 序变得更为复杂的时候就将无法得到很好的扩展。
这里我们首先创建一个叫做requestHandlers的模块,对于每一个请求处理程序都添加一个占位函数:
 代码如下:
function start(){ 
 console.log("Request handler 'start' was called."); 
 
 function sleep(milliSeconds){ 
 var startTime=new Date().getTime(); 
 while(new Date().getTime()
 sleep(10000); 
 return "Hello Start"; 
} 
function upload(){ 
 console.log("Request handler 'upload' was called."); 
 return "Hello Upload"; 
} 
 
exports.start=start; 
exports.upload=upload;
这样我们就可以将请求处理程序和路由模块连接起来,让路由“有路可循”。之后我们确定将一系列请求处理程序通过一个对象来传递,并且需要使用松耦合的方式将这个对象注入到router()函数中,主文件index.js:
 代码如下:
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);
如上所示,将不同的URL映射到相同的请求处理程序上是容易的:只要在对象中添加一个键为“/”的属性,对应 requestHandlers.start即可。这样我们就可以简洁地配置/start和/的请求都交给start这一处理程序来处理。在完成看对象的 定义后,我们将它作为额外的参数传递给服务器,见server.js:
 代码如下:
var http=require("http"); 
var url=require("url"); 
 
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); 
 response.write(content); 
 response.end(); 
 } 
 http.createServer(onRequest).listen(8888); 
 console.log("Server has started."); 
} 
exports.start=start;
这样就在start()函数中添加了handle参数,并且把handle对象作为第一个参数传递给了route()回调函数,下面定义route.js:
 代码如下:
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;
通过以上代码,我们首先检查给定的路径对应的请求处理程序是否存在,如果存在则直接调用相应的函数。我们可以用从关联数组中获取元素一样的方式从 传递的对象中获取请求处理函数,即handle[pathname]();这样的表达式,给人一种感觉就像是在说“嗨,请你来帮我处理这个路径。”程序运 行效果如下图:
 
 
