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); });