为了更深入的了解js,最近开始研究node.js
server.js(服务器启动模块)
var http = require('http');#包含此模块是为了创建服务器
var url = require('url');#包含此模块是为了解析url
function start(route,handle) {
function onRequest(request,response) {
console.log('server received');
var pathname = url.parse(request.url).pathname;#获得请求的路径是start还是upload或是其它
console.log("Request for " + pathname + " received.");
route(handle,pathname,response);#调用route来进行路由分发
}
http.createServer(onRequest).listen(8888);#创建一个http服务器,onRequest回调函数作为参数传递。每当有一个请求到达时,都会交由回调函数来处理
console.log('Server has started.');
}
exports.start = start; #提供其他模块可以使用的方法接口
router.js(路由调度模块)
function route(handle,pathname,response) {
console.log("About to route a request for"+pathname);
if (typeof handle[pathname] === 'function') {
return handle[pathname](response);
#如果handle对象中有此请求url的处理程序,则调用
}else{
console.log("No request handler found for " + pathname);
response.writeHead(404, {"Content-Type": "text/plain"});
response.write("404 Not found"); response.end();
}
}
exports.route = route;
requestHandlers.js(请求处理模块)
var exec = require("child_process").exec;
function start(response) {
console.log("Request handler 'start' was called.");
#在linux根目录下执行find命令,最长时间为10s,将输出的结果用response对象返回到网页,exec方法是异步的,exec的回调函数对请求作出相应,但代码的执行是同步的,所以如果同时请求start和upload,则都可以正常访问。称为非阻塞操作。
exec("find /", { timeout: 10000, maxBuffer: 20000*1024 }, function (error, stdout, stderr) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.write(stdout);
response.end();
});
}
function upload(response) {
console.log("Request handler 'upload' was called.");
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello Upload");
response.end();
}
exports.start = start;
exports.upload = upload;
index.js(主模块)
var server = require("./server.js");
var router = require("./router");
var requestHandlers = require("./requestHandlers");#将已经写好的三个模块包含进来
var handle = {};
handle["/"] = requestHandlers.start;
handle["/start"] = requestHandlers.start;
handle["/upload"] = requestHandlers.upload;#现在此创建一个handle对象,键为请求的url,值为处理此请求的函数
server.start(router.route,handle);