第六课 自己实现路由改进,针对不同请求的路径进行响应

1 server.js

var http = require('http');
var url = require('url');
function start(route,handler)
{
function onRequest(req,res)
{
var pathName = url.parse(req.url).pathname;
//客户端页面传递过来的route 函数
route(pathName,handler,res);
}
http.createServer(onRequest).listen(5000);
console.log('Server Started');
}

exports.start = start;

2 route.js

function route(pathName,handler,res)
{
console.log('router user request url:'+pathName+'\n');
if(typeof handler[pathName]==='function')
{
handler[pathName](res);
}else{
console.log('No request handler found for '+pathName);
}
}
exports.route = route;

 

3 requestHandlers.js

var exec = require('child_process').exec;
//使用 response直接输出 就不会阻塞其他请求
function start(res){
exec("ls -lah",function(error, stdout, stderr){
res.writeHead(200,{"Content-Type":"text/plain"});
res.write('start...');
res.write(stdout);
res.write('end...');
res.end();
});
}

function upload(res){
res.writeHead(200,{"Content-Type":"text/plain"});
res.write(stdout);
res.end();
}

exports.start = start;
exports.upload = upload;

 

4 index.js

var server = require('./server');
var route = require('./route');
var requestHandlers = require('./requestHandlers');
var handle ={}
handle["/"]= requestHandlers.start;
handle["/start"]= requestHandlers.start;
handle["/upload"]= requestHandlers.upload;

server.start(route.route,handle);

//分析 从index.js开始 handle对象存储的是 路由字符串和方法指针

server.js 取得当前用户请求的路径 来执行 路径对应的方法 实际执行的是requestHandlers中的方法

 

posted @ 2015-09-29 21:29  3点破面  阅读(192)  评论(0编辑  收藏  举报