一:效果
打开两个浏览器页面,
第一个浏览器页面输入:http://localhost:8888/upload
第一个浏览器页面输入:http://localhost:8888/start
然后,依次点击进入页面。
隔10秒后,两个页面会依次打开
二:环境
windows7、nodejs
三:代码
1.目录
2.运行文件 index.js
1 var server = require("./server01"); 2 var router = require(‘./router‘); 3 var requestHandlers = require(‘./requestHandlers‘); 4 5 var handle = {} 6 handle["/"] = requestHandlers.start; 7 handle["/start"] = requestHandlers.start; 8 handle["/upload"] = requestHandlers.upload; 9 server.start(router.route, handle);
3.路由文件 router.js
1 function route(handle, pathname){ 2 console.log(‘About to route a request for ‘ + pathname ); 3 if(typeof handle[pathname] === ‘function‘ ){ 4 return handle[pathname](); 5 }else{ 6 console.log(‘No request handler found for ‘ + pathname); 7 return ‘404 not found‘; 8 } 9 } 10 11 exports.route = route;
4.server01.js
1 var http = require("http"); 2 var url = require(‘url‘); 3 4 function start(route, handle){ 5 function onRequest(req, res){ 6 console.log(‘Star : ‘); 7 var pathname = url.parse(req.url).pathname; 8 9 console.log(‘Request for \‘‘ + pathname + ‘\‘ received‘); 10 11 var content = route(handle, pathname); 12 13 res.writeHead(200, {‘Content-Type‘ : ‘text/plain‘}); 14 res.end(content); 15 } 16 17 http.createServer(onRequest).listen(8888,‘127.0.0.1‘); 18 } 19 20 exports.start = start;
4.requestHandlers.js
1 function start(){ 2 console.log(" Request Handler ‘start‘ was called "); 3 function sleep(milliSeconds){ 4 var startTime = new Date().getTime(); 5 while(new Date().getTime() < startTime + milliSeconds); 6 } 7 sleep(10000); 8 return "hello Start"; 9 } 10 11 function upload(){ 12 console.log(" Request Handler ‘upload‘ was called "); 13 return "hello Upload"; 14 } 15 16 exports.start = start ; 17 exports.upload = upload ;
时间: 2024-07-30 10:06:29