node.js学习一例子
访问http://localhost:8888/start, 会有两个textarea,填写相关内容,点提交按钮,会在另外一个页面看到填写的内容。如果两个textarea中的内容很多,node会调用data监听器(request注册的监听器)多次,把数据封装好以后,再调用end监听器中的route路由方法。
1、启动服务器index.js(后台服务器启动使用node index.js):
var server = require("./server");
var router = require("./router");
var requestHandlers = require("./requestHandler");
var handle = {};
handle["/"] = requestHandlers.start;
handle["/start"] = requestHandlers.start;
handle["/upload"] = requestHandlers.upload;
server.start(router.route, handle);
2、服务器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.");
var postData="";
//response.writeHead(200, {"Content-Type": "text/plain"});
//var content = route(handle, pathname);
//response.write(content);
// response.end();
//route(handle,pathname,response);
request.setEncoding("UTF-8");
request.addListener("data", function(postDataChunk){
postData += postDataChunk;
console.log("Received Post data chunk '" + postDataChunk + "'.");
});
request.addListener("end", function(){
route(handle, pathname, response, postData);
});
}
http.createServer(onRequest).listen(8888);
console.log("Server has started.");
}
exports.start = start;
3、路由选择route.js
function route(handle,pathname,response, postData){
console.log("About to route a request for " + pathname);
if(typeof handle[pathname] == 'function'){
return handle[pathname](response, postData);
}else{
console.log("No request handler found for " + pathname);
//return "404 Not Found!";
response.writeHead(404, {"Content-Type":"text/plain"});
response.write("404 Not found");
response.end();
}
}
exports.route = route;
4、请求处理requestHandler.js
var exec = require("child_process").exec;
function start(response, postData){
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" method="post">' +
'<textarea name="text" rows="20" cols="60"></textarea>' +
'<textarea name="text2" rows="20" cols="60"></textarea>' +
'<input type="submit" value="Submit text"/>' +
'</form>' +
'</body>' +
'</html>';
response.writeHead(200, {"Content-Type":"text/html"});
response.write(body);
response.end();
}
function upload(response, postData){
console.log("Request handler 'upload' was called");
//return "Hello Upload";
response.writeHead(200, {"Content-Type":"text/plain"});
response.write("You've sent: " + postData);
response.end();
}
exports.start = start;
exports.upload = upload;