This article introduces the timeout event in nodejs, and provides a detailed example analysis, which is very detailed, if the server does not respond within the specified time period (it may be due to a problem with the connection between networks, it may also be because the server fails or the network firewall blocks the connection between the client and the server), the response times out, And the http. timeout event of the ServerResponse object.
Response. setTimeout (time, [callback]);
You can also not specify the callback function in setTimeout. You can use the time listening method to specify the callback function.
If no time-out callback function is specified, the socket port connected to the http client is automatically closed when the time-out occurs. if a time-out callback function is specified, a callback function is called and the socket port connected to the http client is not automatically closed.
The Code is as follows:
Var http = require ("http ");
Var server = http. createServer (function (req, res ){
If (req. url! = "/Favicon. ico "){
// Timeout listener
/* Res. setTimeout (1000 );
Res. on ("timeout", function (){
Console. log ("response timeout .");
});*/
// Direct callback upon timeout
Res. setTimeout (1000, function (){
Console. log ("response timeout .");
});
SetTimeout (function (){
Res. setHeader ("Content-Type", "text/html ");
Res. write (" ");
Res. write ("hello ");
Res. end ();
},2000 );
}
});
Server. listen (1337, "localhost", function (){
Console. log ("Start listening" + server. address (). port + "......");
});
Running code result:
After deleting the expired callback function: