Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 950
murvinlai Avatar asked Jul 12 '11 02:07

murvinlai


1 Answers

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

like image 98
Andrey Sidorov Avatar answered Sep 28 '22 23:09

Andrey Sidorov