日期:2014-05-16 浏览次数:20353 次
var server = require("./server"); var router = require("./router"); var requestHandlers = require("./requestHandlers"); var handle = {}; //包含处理函数,此处不能声明为 var handle = [];原因:[]的index只接受数字。{}的index才支持任意可hash的类型。 handle["/"] = requestHandlers.start; handle["/start"] = requestHandlers.start; handle["/upload"] = requestHandlers.upload; handle["/show"] = requestHandlers.show; server.start(router.route,handle);
var http = require("http"); var url = require("url"); var formidable = require("formidable"); //必须要下在formidable模块,可以使用npm下载 function start(route,handle){ function onRequest(req,res){ pathname = url.parse(req.url).pathname; //得到路径 var postData = ""; console.log("Pathname--------------:" + pathname + " is coming"); route(handle,req,res,pathname); //调用路由函数 } http.createServer(onRequest).listen(8080); console.log("server is starting"); }; exports.start = start; //暴露start函数
function route(handle,req,res,pathname){ console.log("route a request for: " + pathname) if(typeof handle[pathname] === 'function'){ handle[pathname](req,res); return; }else{ console.log("No Request Path----???????"); res.writeHead(200,{"Content-Type":"text/html"}); res.write("404 Not Found"); res.end(); } } exports.route = route;
var querystring = require("querystring"), fs = require("fs"), exec = require("child_process").exec, formidable = require("formidable"); function start(req,res){ console.log("Request handler 'start' was called."); var body = '<html>'+ '<head>'+ '<meta http-equiv="Content-Type" content="text/html; '+ 'charset=UTF-8" />'+ '</head>'+ '<body>'+ '<form action="/upload" enctype="multipart/form-data" method="post">'+ '<input type="file" name="upload" multiple="multiple"/>'+ '<input type="submit" value="UploadPic" />'+ '</form>'+ '</body>'+ '</html>'; res.writeHead(200, {'Content-Type' : 'text/html'}) res.write(body); res.end(); } function upload(req,res){ console.log("Upload:" + req + " ---- ==="); var form = new formidable.IncomingForm(); form.parse(req,function(error,fields,files){ console.log("parsing is over"); fs.renameSync(files.upload.path,"/tmp/test.png"); res.writeHead(200,{"Content-Type":"text/html"}); res.write("received image:<br/>"); res.write("<img src='/show'/>"); res.end(); });; } function show(req,res){ console.log("show"); fs.readFile("/tmp/test.png","binary",function(error,file){ if(error){ res.writeHead(500,{"Content-Type":"text/plain"}); res.write(error+"\n"); res.end(); }else{ res.writeHead(200,{"Content-Type":"image/jpg"}); res.write(file,"binary"); res.end(); } }); } exports.start = start; exports.upload = upload; exports.show = show;
Administrator@WIN-23C1Q4GKQ4G ~ $ node /example/index.js server is starting Pathname--------------:/start is coming route a request for: /start Request handler 'start' was called. Pathname--------------:/upload i