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 exe开发者_StackOverflowcution will hang there and will not end. What can I do to stop it? (other than process.exit());
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
Call res.req.destroy()
.
See: https://nodejs.org/api/http.html#requestdestroyerror
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) .
精彩评论