好,我们马上开始介绍,如何以正确的方式,把耗时又不阻塞的内容让浏览器作出响应
到现在为止,我们的代码已经可以通过各个模块之间传递返回值
requestHandler->routes->server
最后在server中通过 response.write 回写到浏览器中
现在我们改一下,不再传递字符串的返回值,而是直接传递response对象, 把response对象,从server->routes->requesthanler传下去。
首先是server.js, 把response, 向下传递给routes, 同时删除所有的response返回,交给下面的requestHanler处理。
到现在为止,我们的代码已经可以通过各个模块之间传递返回值
requestHandler->routes->server
最后在server中通过 response.write 回写到浏览器中
现在我们改一下,不再传递字符串的返回值,而是直接传递response对象, 把response对象,从server->routes->requesthanler传下去。
首先是server.js, 把response, 向下传递给routes, 同时删除所有的response返回,交给下面的requestHanler处理。
function start(get, config){
var http = require("http");
var url = require("url");
var server = http.createServer(function(request, response){
var pathname = url.parse(request.url).pathname;
get(pathname, config, response);
});
server.listen(8888);
}
exports.start = start;
下面是 routes.js, 接收server传来的response , 并进一步向下传递给requestHandler
function get(pathname , config, response){
console.log("routes to :"+pathname);
if (typeof(config[pathname]) === 'function') {
config[pathname](response);
} else{
console.log("routes to empty path: " + pathname);
}
};
exports.get = get;
最后是 requestHandler
var exec = require("child_process").exec;
function a(response){
response.writeHead(200,{"Content-Type":"text/plain"});
response.write("visit path /a");
response.end();
}
function b(response){
var content = "empty";
exec("ls -al", function(error, stdout, stderr){
response.writeHead(200, {"Content-Type":"text/plain"});
response.write(stdout);
response.end();
});
}
exports.a = a;
exports.b = b;
运行 node index.js ,浏览器中访问 http://localhost:8888/b 你将能在浏览器中看到
total 20
drwx------+ 1 Administrators None 0 Jun 16 12:20 .
drwx------+ 1 Administrators None 0 Jun 14 20:27 ..
-rwx------+ 1 Administrators None 246 Jun 16 11:07 index.js
-rwx------+ 1 Administrators None 1379 Jun 16 11:54 lesson-08.zip
-rwx------+ 1 Administrators None 423 Jun 16 12:18 requestHandler.js
-rwx------+ 1 Administrators None 320 Jun 16 12:14 routes.js
-rwx------+ 1 Administrators None 301 Jun 16 12:20 server.js
drwx------+ 1 Administrators None 0 Jun 11 13:54 tmp
注这次因为要执行的是 ls ,所以,windows自带的dos窗口中运行的话,你看到的浏览器可以是一片空白,所以请用 cygwin 或者 git-bash 等支持 ls 这个命令的CLI中运行
如果还想继续证明 /b 里的耗时操作不会阻塞对 /a 的请求作出立即响应,可以把requestHanler 修改为
如果还想继续证明 /b 里的耗时操作不会阻塞对 /a 的请求作出立即响应,可以把requestHanler 修改为
exec("find /",
{timeout:10000, maxBuffer:20000*1024},
function(error, stdout, stderr){
response.writeHead(200, {"Content-Type":"text/plain"});
response.write(stdout);
response.end();
});
重启node index.js
先访问耗时的 http://localhost:8888/b, 再访问 http://localhost:8888/a
可以看到, /a这回很快就返回了 visit path /a
过了好久 /b 才返回
/ /bin
/bin/2to3
/bin/addftinfo.exe
/bin/addr2line.exe ....
/b 再耗时也不会阻塞 其它的响应了(/a)
收工!
本课代码下载:
lesson-09.zip |