How to destroy a Node.js http.request connection nicely?

murvinlai picture murvinlai · Jul 12, 2011 · Viewed 12.8k times · Source

If I run it in the command line, the program will stop after client.destroy();

var client = http.get(options, 
        function(res) {
            console.log(res.statusCode);
            client.destroy();
          }
);

However, it is not the case when I put the client.destroy() inside the res.on('end'):

var client = http.get(options, 
        function(res) {
            console.log(res.statusCode);
            res.on('end', function() {
                console.log("done");
                client.destroy();
            });
          }
);

It will throw exception because the http.socket is null. so, I can't destroy it.

IN this case, the program execution will hang there and will not end. What can I do to stop it? (other than process.exit());

Answer

Andrey Sidorov picture Andrey Sidorov · Jul 12, 2011

if it's single request you can just set shouldKeepAlive to false

var request = http.get(options, 
        function(res) {
            console.log(res.statusCode);
          }
);
request.shouldKeepAlive = false

or send Connection: close header

You can't access socket because it is detached in the request 'end' event handler