cathy.sasaki
cathy.sasaki

Reputation: 4025

How does the event: 'close' work in Node.js?

I'm experimenting with the close event in Node.js. I'm very new to Node.js so I'm not sure if this is a decent question or a sad one.

Documentation for close event: http://nodejs.org/api/http.html#http_event_close_2

I want to output to the console a message if the browser is closed before the end event is reached.

While the server ran and before it got to 15 seconds, I tried closing the browser and killing the process through Chrome Tools. No message is output to the console and if I open up other connections by visiting localhost:8080 with other windows, I quickly get a 'hello' indicating my node server thinks there are at least two connections.

I'm either not understanding how to kill processes in Chrome or how the event close works.

Or if End and Close are the same - node.js https no response 'end' event, 'close' instead? - why isn't my "They got impatient!" message still ouput in the console?

How can you output to a console if the process was ended before the event end was reached?

var http = require('http'),
    userRequests = 0;


http.createServer(function(request,response){
userRequests++;

response.writeHead(200, {'Content-Type' : 'text/plain'});

if ( userRequests == 1 ){

    response.write('1st \n');
    setTimeout ( function() {
        response.write('2nd Thanks for waiting. \n');
        response.on('close', function() {

            console.log("They got impatient!");

        });
        response.end();
    }, 15000);
    response.write('3rd \n');
}
else {
    // Quick response for all connections after first user
    response.write('Hello');
    response.end();
}
}).listen(8080, function() {
console.log('Server start');
});

Thank you.

Upvotes: 1

Views: 2148

Answers (1)

Chris Tavares
Chris Tavares

Reputation: 30411

First - move the event handler for the close message outside the timeout function - you're not hooking up the close handler until after your timeout expires, and probably missing the event.

Second, you never decrement userRequests anywhere; shouldn't there be a userRequests--; line somewhere? This would be throwing off your logic, since it'll always look like there's more than one request.

Upvotes: 2

Related Questions