Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js server 'close' event doesn't appear to fire

Tags:

node.js

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?

like image 896
AJcodez Avatar asked Sep 09 '13 06:09

AJcodez


People also ask

How do I fire events in Node JS?

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.

What is an event-driven application in Node JS?

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:

Why'Connect'event is not working in socket Io?

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.


1 Answers

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);
  });
});
like image 170
Michelle Tilley Avatar answered Sep 17 '22 13:09

Michelle Tilley