Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js https no response 'end' event, 'close' instead?

Tags:

I am using node.js v. 0.4.8. When I create a HTTPS server, I never get the response.on('end', ...) event (but I do for a HTTP one). I read the issue reports on node's github page - https://github.com/joyent/node/issues/728, and apparently this is an issue that regressed into 0.4.8. response.on('close', ...) seems to have the same functionality, but I do not know enough about HTTP/HTTPS to judge. Can I use it as replacement for response.on('end', ...), and is this likely to cause any problems in future?

You can see a code sample below. Thanks in advance!

var request = "JSON_request";
var https = require('https');
var options = { 
        host:"someHost.com",
        path:"somePath",
        method: "POST", 
        headers: {
            'Content-Type': 'application/json',
            'Content-Length': Buffer.byteLength(request)
        }
    };

var req = https.request(options, function(res){
    var response = "";
    res.setEncoding('utf8');

    res.on('data', function(chunk){
        console.log("INFO: "+chunk);
        response += chunk;
    });

    // This never happens
    res.on('end', function(){
        console.log("End received!");
    });

    // But this does
    res.on('close', function(){
        console.log("Close received!");
    });
});

req.on('error', function(error){
    console.log("Error: "+error);
});

req.write(request);
req.end();
like image 926
Nikola Chonkov Avatar asked Jun 30 '11 15:06

Nikola Chonkov


2 Answers

I believe this issue has been fixed as of commit de09168, and there hasn't been any action on this question for months BUT here is the answer:

On the comments for issue 728 Node.js creator Ryan Dahl says:

This isn't a bug. Responses are not guaranteed to have an 'end' event. Use 'close'.

Though later he says:

i take back what i said before. we should probably make this work.

Either way it seems close and end are pretty much interoperable in this use case. The relevent code in the node.js core tls.js:681 renforces that interpretation:

process.nextTick(function() {
  self.encrypted.emit('end');
  self.cleartext.emit('end');
  self.encrypted.emit('close');
  self.cleartext.emit('close');
});
like image 183
Daniel Mendel Avatar answered Sep 20 '22 01:09

Daniel Mendel


Since node.js 0.8.12 finish event is emitted on HTTP responses' end function. I wrote all the details in a similar question.

like image 24
Dario Castañé Avatar answered Sep 24 '22 01:09

Dario Castañé