4

I've been experimenting with domains in node JS. The code does what I expect it to, but when the code has completed, node doesn't exit cleanly, which makes me think there's some uncollected garbage or something that I don't understand. Any suggestions? Here's a cut-down example:

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); });
Josh Lee
  • 171,072
  • 38
  • 269
  • 275
Dave Cleal
  • 41
  • 1
  • I unfortunately don't know much about domains yet, but want to learn more about them. I noticed that when you encounter an error, you call d.dispose(), but never call d.dispose() for successes. Not sure if that is the culprit or not. – Brandon Mar 18 '13 at 20:38
  • yes - I'm not clear about that either. I put it in when I first saw the code not exitting, in case it was necessary: the doc implies it will help to clear up any loose ends. But it made no difference. – Dave Cleal Mar 18 '13 at 21:05

0 Answers0