首页 > nodejs http阻塞与非阻塞

nodejs http阻塞与非阻塞

Node入门中, 有关于阻塞与非阻塞。如果使用route来返回结果会阻塞, 而使用传递response的方式就不会阻塞,有谁能解释一下吗?

使用route返回结果会阻塞:

 function onRequest(request, response) {
        var pathname = url.parse(request.url).pathname;
        console.log('Request for ' + pathname + ' received.');
        var content = route(handler, pathname);
        response.writeHead(200, {'Content-Type':'text/plain'});
        response.write(content);
        response.end();
    }
    http.createServer(onRequest).listen(8888);
    console.log('Server started at port: 8888');

传递response则不会阻塞:

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.");

PS: js的异步与事件机制我了解,但是感觉这里http封装起来就看不懂那些地方是异步了。


如果你再看一下书中,这个和使用不使用route没有关系,route仅仅是一个函数,而且在两种情况下都不一样。这里的关键是在

content = route(handler, pathname);

你必须等route函数返回结果,才可以进行下一步的response,这样子就造成blocking了。而在

route(handle, pathname, response);

response作为参数传到了route函数里面,在route函数里面用了回调来避免了blocking的发生。

【热门文章】
【热门文章】