Node.js server 'close' event doesn't appear to fire
Killing the server with Ctrl+C
doesn't allow the server to close itself; you have to do this yourself. Something like this should do the trick (on UNIX-like systems):
var http = require('http');
var server = http.createServer();
server.on('close', function() {
console.log(' Stopping ...');
});
process.on('SIGINT', function() {
server.close();
});
server.listen(8000);
Once the HTTP server closes and Node realizes there are no async operations that could be pending, it will automatically stop the process. If you have other stuff on the event loop (timers, etc.) and you want to force the event loop to stop after the server closes, close
takes a callback:
process.on('SIGINT', function() {
server.close(function() {
process.exit(0);
});
});
You added an event handler for close
. Use server.close();
to trigger the server event.