Analysis of close events in node.js
- 2020-03-30 04:26:12
- OfStack
The close event of the http.serverresponse object is triggered if the connection is broken before the end method of the http.serverresponse object is called.
var http=require("http");
var server=http.createServer(function(req,res){
if(req.url!=="/favicon.ico"){
res.on("close",function(){
console.log(" Connect the interrupt ")
});
setTimeout(function(){
res.setHeader("Content-Type","text/html");
res.write("<html><head><meta charset='utf-8' /></head>");
res.write(" hello ");
res.end();
},10000);
}
});
server.listen(1337,"localhost",function(){
console.log(" To start listening to "+server.address().port+"......");
});
The above code looks like this:
When the client makes a request, send "hello" to the client after 10 seconds. Meanwhile, listen for the close event.
As soon as the server is shut down within 10 seconds, the server is "disconnected" because the res.end() method is not executed for 10 seconds.