I’ve got an app that fires off https requests to a 3rd party service to perform logging. For some reason or another I noticed a few hours ago that the 3rd party is refusing the connections. That’s a different topic though.
What I’m noticing in my node.js app is that despite the requests being created dynamically, and therefore shouldn’t be hanging the entire app, they are.
After a restart of the process, the https request is hanging and then dies with a connection refused error. Sample code is below.
var logger = function(data){
var req = https.request({
host: 'logs.loggly.com',
port: 443,
path: '/inputs/<my real key is here, removed obviously>',
method: 'POST',
headers:{
'content-type': 'application/json'
}
}, function(res){
var body = [];
res.on('chunk', function(data){
body.push(data);
});
res.on('end', function(){
console.log(body.join(''));
})
});
req.write(JSON.stringify(data));
req.end();
}
And that’s called simply by:
logger({ 'test': 'datafoo' });
So I’m curious why a connection refused/timeout from this outbound https request should be hanging and then crashing the entire app.
Thanks!
The program hangs and prints nothing because it’s not catching data and you’re not telling the process to do anything but print an empty string with
[].join(''). Node.js won’t return without explicit instruction on IO-bound tasks. You need to pass in and execute a callback function, or callprocess.exit();, in the handler forres.on("end", [handler]);, e.g.:res.on("end", function() { console.log(body.join('')); process.exit(); });res.on("chunk", [handler]);isn’t a standard HTTPS event. You likely intended something likeres.on("data", function(chunk) { body.push(chunk); });.