When running my Express application in production, I want to shut down the server gracefully when its process is killed (i.e. a SIGTERM or SIGINT is sent).
Here is a
If you allow me, there is even a better solution that involves less work by using server-destroy
package. Internally this package will terminate gracefully each connection and then allow the server to be "destroyed". In this case we ensure to definitively end the express application (and potentially start it again if we use a call function). This works for me using electron, and can potentially be ported to a standard server:
const express = require('express')
const { ipcMain } = require('electron')
const enableDestroy = require('server-destroy')
const port = process.env.PORT || 3000
export const wsServer = () => {
try {
let app = null
let server = null
const startServer = () => {
if (app) {
app = null
}
app = express()
app.use(express.static('public'))
app.use('/', (req, res) => {
res.send('hello!')
})
server = app.listen(3000, () => {
console.log('websocket server is ready.')
console.log(`Running webserver on http://localhost:${port}`)
})
enableDestroy(server)
}
const stopServer = () => {
if (server !== null) {
server.destroy()
app = null
server = null
}
}
const restartServer = () => {
stopServer()
startServer()
}
ipcMain.on('start-socket-service', (event) => {
startServer()
console.log('Start Server...')
event.returnValue = 'Service Started'
})
ipcMain.on('stop-socket-service', (event) => {
stopServer()
console.log('Stop Server...')
event.returnValue = 'Service Stopped'
})
ipcMain.on('restart-socket-service', () => {
restartServer()
})
} catch (e) {
console.log(e)
}
}