标签:回调 load export 模块 create bsp 一个 情况 nodejs
在最开始,我们要弄清楚node会什么会存在阻塞?
node是这么标榜自己的:“在node中除了代码,所有一切都是并行执行的!”
意思是,Node.js可以在不新增额外线程的情况下,依然可以对任务进行并行处理 —— Node.js是单线程的。
也就是说,我们启动的web服务器,监听8888端口的start方法,是单线程的。
如果某一个请求耗时,那么后面的请求要等上一个请求完成之后才执行,这显然是不合理的!
如requestHandlers中start handler:
function start() { console.log("Request handler ‘start‘ was called."); function sleep(milliSeconds) { var startTime = new Date().getTime(); while (new Date().getTime() < startTime + milliSeconds); } sleep(10000); return "Hello Start"; }
我们可以使用child_process模块来实现非阻塞操作,其实就是一个异步操作,强调一点,耗时操作通常都需要通过异步操作来处理。
一种错误的示范:
var exec = require("child_process").exec; function start() { console.log("Request handler ‘start‘ was called."); var content = "empty"; exec("ls -lah", function (error, stdout, stderr) { content = stdout; }); return content; } function upload() { console.log("Request handler ‘upload‘ was called."); return "Hello Upload"; } exports.start = start; exports.upload = upload;
错误原因,exec异步操作后面的不能再跟同步代码,一个简单的例子,juqery ajax请求成功后的后续操作应该在success中处理,而不应该再ajax整个代码块后面处理。
既然后续操作都要在异步回调函数中实现,所以response的处理就要移步至handler中实现。
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;
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;
requestHandler.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;
标签:回调 load export 模块 create bsp 一个 情况 nodejs
原文地址:http://www.cnblogs.com/anybus/p/7724994.html