eisbehr eisbehr - 3 months ago 15
Node.js Question

execute event on process termination with node.js

Is there a way with

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

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


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)