我們要將response物件(從伺服器的回呼函數onRequest()取得)透過請求路由傳遞給請求處理程序。隨後,處理程序就可以採用該物件上的函數來回應請求。
我們先對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.");
route(handle, pathname, response);
}
http.createServer(onRequest).listen(8888);
console.log("Server has started.");
}
exports.start = start;
我們將response物件作為第三個參數傳遞給route()函數,並且,我們將onRequest()處理程序中所有有關response的函數調都移除,因為我們希望這部分工作讓route()函數來完成。
接下來修改 router.js:
function route(handle, pathname, response) {
console.log("About to route a request for " pathname);
if (typeof handle[pathname] === 'function') {
handle[pathname](response);
} 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;
同樣的模式:相對先前從請求處理程序中取得回傳值,這次取而代之的是直接傳遞response物件。 如果沒有對應的請求處理器處理,我們就直接回傳「404」錯誤。
接下來修改requestHandler.js:
var exec = require("child_process").exec;
function start(response) {
console.log("Request handler 'start' was called.");
exec("ls -lah", 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;
我們的處理程序函數需要接收response參數,為了對請求作出直接的回應。 start處理程序在exec()的匿名回呼函數中做請求回應的操作,而upload處理程序仍然是簡單的回應“Hello World”,只是這次是使用response物件而已。
如果想要證明/start處理程序中耗時的操作不會阻塞對/upload請求作出立即回應的話,可以將requestHandlers.js修改為如下形式:
var exec = require("child_process").exec;
function start(response) {
console.log("Request handler 'start' was called.");
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;
這樣一來,當請求http://localhost:8888/start的時候,會花10秒鐘的時間才載入,而當請求http://localhost:8888/upload的時候,會立即回應,縱然這個時候/start響應還在處理中。