eisbehr eisbehr - 1 month ago 7
Node.js Question

execute event on process termination with node.js

Is there a way with

node.js
to execute an event on termination of an process? For example, when a
express
server is runing in console and I hit
CTRL+C
it should write a log somewhere.

I tried it with
process.on('exit', ...
what was not working. I think this is only executed on
process.exit()
. So I'm searching for a general way to detect termination or kill of an process.

Answer

You can catch Ctrl + C using SIGINT

process.on('SIGINT', () => {
  console.log('Log that Ctrl + C has been pressed');
})

However this prevents the default action so you will also have to call process.exit() after logging your message

This will only catch Ctrl + C though it will not catch things like End Task in Windows etc

You may also want to listen on SIGTERM (termination on linux), SIGHUP (close console on windows) and SIGBREAK (Ctrl+Break on Windows)

Comments