NodeJS域模块不会干净地退出

时间:2013-03-18 20:26:12

标签: node.js error-handling node.js-domains

我一直在尝试使用节点JS中的域名。代码完成了我的预期,但是当代码完成后,节点不会干净地退出,这让我觉得有一些未收集的垃圾或我不理解的东西。有什么建议?这是一个简单的例子:

var https = require('http');
var domain = require('domain');

function getUrl(aHost, aPath, okCallback) {
  var options = { host : aHost, path : aPath, method : 'GET' }
    , responseBody = ''
    , request = https.request(options, handleRequest);

  request.end();

  function handleRequest(httpsResponse) {
    httpsResponse.setEncoding('utf8');
    httpsResponse.on('data', function(chunk) { responseBody += chunk; });
    httpsResponse.on('end',  function(){ okCallback(httpsResponse.statusCode, responseBody); });
  }
}

function fetch(aHost, aPath, okCallback) {
  var d = domain.create();
  d.on('error', function(err) { 
    console.log('It all went awry: ' + err.toString());
    d.dispose();
  });

  d.run(function() { getUrl(aHost, aPath, d.bind(storeResult)); });

  function storeResult(statusCode, responseBody) {
    if (statusCode >= 400) {
      throw new Error("Oops");
    } else {
      okCallback(responseBody);
    }
  }
}

// works fine and exits cleanly with a valid path (like '/')
fetch('www.google.com', '/invalidPath', function(body) { console.log('Received: ' + body); });

0 个答案:

没有答案