0

I am trying to create a close event that fires before the server shuts down.

for this ive created the following:

var express = require('express');
var app = express();
var http = require('http').Server(app);
var listenTo = require('./config/port.json')["port"];


http.listen(listenTo, function () {
    console.log('listening on *:' + listenTo);
});

http.on('close', function (event) {
    console.log('closed');
});

However this just shuts down the server.

So my question is how can i listen on server shut down using http

Marc Rasmussen
  • 19,771
  • 79
  • 203
  • 364
  • Check [this](http://stackoverflow.com/questions/18692536/node-js-server-close-event-doesnt-appear-to-fire) out, I think you are using a method that closes the server instead of listening to close events. – realappie Mar 13 '17 at 09:01

1 Answers1

3

Instead of listening for the event, you are closing the server.

Instead of this:

http.close(function (event) {
    console.log('closed');
});

you should use this:

http.on('close', function (event) {
    console.log('closed');
});

Compare this:

with this:

Note that if you want to handle events of closing the server application (terminating the process) and not just closing the http server (closing the open port) then you need to handle a different kind of events, like:

process.on('SIGINT', function () {
    console.log('SIGINT caught');
    // if you want to exit then call:
    process.exit();
});
rsp
  • 107,747
  • 29
  • 201
  • 177
  • I have attempted this and tried CTRL + C in my console but it doesnt fire an event. am i missing something i have updated my code to what you suggested – Marc Rasmussen Mar 13 '17 at 13:24
  • @MarcRasmussen if you want to capture Ctrl+C then see my updated answer. – rsp Mar 20 '17 at 15:26