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

3

8

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

Clere answered 12/7, 2011 at 2:3 Comment(0)
K
7

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

Krugersdorp answered 12/7, 2011 at 3:4 Comment(3)
when I do 'request.shouldKeepAlive" , does it affect anything on the socket pooling?Clere
it probably better to use Connection header, it is analysed here - github.com/joyent/node/blob/master/lib/http.js#L442 This affects request shouldKeepAlive flagKrugersdorp
Guys, stop linking line numbers in "master" -- it's useless -- you can't link a line number on a moving target.Pantaloon
M
1

Call res.req.destroy().

See: https://nodejs.org/api/http.html#requestdestroyerror

Montymonument answered 12/3, 2022 at 10:56 Comment(0)
C
0

To your question: request created by http.get or http.request will close its socket(connection) by default. You don't have to close it.

To your code example: Nodejs has registered res.on('end', responseOnEnd) before your "res.on('end', yourCb)". responseOnEnd will close the socket. Because responseOnEnd is called before yourCb,so you can't destory the socket in res.on('end', yourCb) .

Coenobite answered 27/2, 2022 at 10:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.