1. 程式人生 > >nodejs入門學習筆記二——解決阻塞問題

nodejs入門學習筆記二——解決阻塞問題

rtti 線程 需要 std 額外 tar fun 自己 我們

  在最開始,我們要弄清楚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;

nodejs入門學習筆記二——解決阻塞問題