Reputation: 85
I'm using nodemon in my nodejs app to auto restart when changes apply. But when I stop nodemon using 'Ctrl + C' in ubuntu environment, doesn't stop nodejs. I have to search the process that's running from the port and have to kill manually using kill -9 . How can I fix this?
Upvotes: 1
Views: 3261
Reputation: 5519
Quick and dirty solution
process.on('SIGTERM', stopHandler);
process.on('SIGINT', stopHandler);
process.on('SIGHUP', stopHandler);
function stopHandler() {
console.log('Stopped forcefully');
process.exit(0);
}
Right solution
Implementing Graceful Shutdown
is a best practise. At this example, I should only stop the server. If the server will stop longer than 2s, then the process will terminate with exitcode 1
.
process.on('SIGTERM', stopHandler);
process.on('SIGINT', stopHandler);
process.on('SIGHUP', stopHandler);
async function stopHandler() {
console.log('Stopping...');
const timeoutId = setTimeout(() => {
process.exit(1);
console.error('Stopped forcefully, not all connection was closed');
}, 2000);
try {
await server.stop();
clearTimeout(timeoutId);
} catch (error) {
console.error(error, 'Error during stop.');
process.exit(1);
}
}
Upvotes: 3