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.
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.
Share Improve this question asked Apr 29, 2016 at 16:41 JQuery MobileJQuery Mobile 6,30124 gold badges88 silver badges138 bronze badges 6-
Not sure why you're using backticks in your
console.log
entry. That seems like a mistake. – tadman Commented Apr 29, 2016 at 16:44 -
1
Also do you mean the
exit
event? – tadman Commented Apr 29, 2016 at 16:45 - 2 @tadman The backticks are es6 template strings. – Ad.Infinitum Commented Apr 29, 2016 at 16:58
- @Ad.Infinitum Learn something new every day. Thanks! – tadman Commented Apr 29, 2016 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 Commented Apr 29, 2016 at 17:44
3 Answers
Reset to default 9You 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);
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.
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?