4

I have a Node.js app that uses Express. In that app, I have a block that looks like this:

const app = require('./app');
const port = process.env.PORT || 8080;
const server = app.listen(port);

server.on('listening', () =>
  console.log(`Application launched on ${app.get('host')}:${port}`)
);

This successfully works. It successfully prints the message when the listening event is fired. My question is, is there any event I can listen for, for when my server is stopped / shutting down? Or when the server stops listening?

I would like to do some cleanup in this scenario.

JQuery Mobile
  • 6,221
  • 24
  • 81
  • 134
  • Not sure why you're using backticks in your `console.log` entry. That seems like a mistake. – tadman Apr 29 '16 at 16:44
  • 1
    Also do you mean the [`exit` event](https://nodejs.org/api/process.html#process_event_exit)? – tadman Apr 29 '16 at 16:45
  • 2
    @tadman The backticks are es6 template strings. – Ad.Infinitum Apr 29 '16 at 16:58
  • @Ad.Infinitum Learn something new every day. Thanks! – tadman Apr 29 '16 at 17:19
  • sorry for going off-topic, but this is the first time I see someone with a reputation of 268 and 10 gold badges :P – Yerken Apr 29 '16 at 17:44
  • it depends what kind of clean up, normally you would want to track those things on a higher level. If you are using some process launching mechanism, be it `upstart` or some `node`-specific `pm2` or `forever` you can make sure that the process restarts on crash, or in case of `upstart` perform a clean up. – Yerken Apr 29 '16 at 17:47

3 Answers3

8

You could listen to node's process events for shutdown

// listen for TERM signal .e.g. kill
process.on ('SIGTERM', doSomething);

// listen for INT signal e.g. Ctrl-C
process.on ('SIGINT', doSomething); 

//or even exit event 

process.on('exit',doSomething); 
1

You should be able to trap this with exit:

process.on('exit', function() {
  console.log('Process terminating.')
});

As pointed out in the documentation you cannot defer anything, this is a one shot deal.

tadman
  • 208,517
  • 23
  • 234
  • 262
  • where does `process` come from? – JQuery Mobile Apr 29 '16 at 19:39
  • It should be a global that always exists within Node. – tadman Apr 29 '16 at 19:44
  • do I need to add process.exit(1) inside the function? – Kid Jan 16 '20 at 16:56
  • @O.o This is the exit handler, so that's already been called. This is just an opportunity to do some housekeeping before it terminates. You're not responsible for effecting the termination itself. – tadman Jan 16 '20 at 21:48
  • Btw, when I worked with React.JS before, I sometimes felt that console.log took some time, and if so, is there any chance to not being shown the `process terminating`? – Kid Jan 17 '20 at 00:31
  • That's usually the case of an exit being initiated, but something's still "running" in an async sense. You may have an outstanding promise, timer, or interval that hasn't yet tripped. – tadman Jan 17 '20 at 03:06
0

You can also use promises along the following lines to make everything nice and synchronous:

#!/usr/bin/env node
(async () => {
const express = require('express')
const app = express()
app.get('/', (req, res) => {
  res.send('hello world')
})
await new Promise((resolve, reject) => {
  const server = app.listen(3000, function () {
    console.log('Server started')
    // If you wanted to test this code, you could close it here.
    // this.close()
  })
  server.on('close', resolve)
})
console.log('After listen')
})()

Related: How to synchronously wait for express.js HTTP server to close after a listen call?

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985