In the Node docs, http servers appear to have a close event:
Event: 'close'
function () { }
Emitted when the server closes.
But I can't figure out how to trigger it:
// server.js
var http = require('http');
var server = http.createServer();
server.on('close', function() {
console.log(' Stopping ...');
});
server.listen(8000);
I expected the message "Stopping ..."
$ node server.js
^C Stopping ...
$
But instead there's nothing
$ node server.js
^C$
Does close mean something else here?
Objects in Node.js can fire events, like the readStream object fires events when opening and closing a file: Node.js has a built-in module, called "Events", where you can create-, fire-, and listen for- your own events.
Node.js is perfect for event-driven applications. Every action on a computer is an event. Like when a connection is made or a file is opened. Objects in Node.js can fire events, like the readStream object fires events when opening and closing a file:
Make sure that both client and server have same major version of socket.io. For example, combination of [email protected] on server and [email protected] at client leads to this case and the 'connect' event is not dispatched.
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);
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With