4

我一直在试验节点 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); });
4

0 回答 0