i have this node code that detect when Ctrl+C in pressed to that do some stuff before node app is exit
process.on('SIGINT', function() {
/* DO SOME STUFF HERE */
process.exit()
})
Now this works but i would like to add to this process others terminations signals so that when Ctrl+C, Node app exits or server is restarted or shutdown or any other reason node app exits to trigger termination signal and call this process and do stuff in database before exits...
termination signals that i need to add is:
SIGTERM
SIGINT
SIGQUIT
SIGKILL
So i came to idea if is possible to do this:
process.on('SIGINT', 'SIGTERM', 'SIGQUIT', 'SIGKILL', function() {
/* DO SOME STUFF HERE */
process.exit()
})
So to pass multiple termination signals to process function..i added like this above but it does not work...how can this be done in node js?
Pressing Ctrl+C sends an Interrupt signal (SIGINT) to the process and the process terminates. Restart it. Pressing Ctrl+Z sends a STOP signal (SIGTSTP) to the process which kind of freezes/pauses the process and the shell prompt returns.
SIGINT is the signal sent when we press Ctrl+C. The default action is to terminate the process. However, some programs override this action and handle it differently.
SIGINT is nearly identical to SIGTERM. The SIGTSTP signal is sent to a process by its controlling terminal to request it to stop temporarily. It is commonly initiated by the user pressing Ctrl-Z. Unlike SIGSTOP, the process can register a signal handler for or ignore the signal.
process. cwd() returns the current working directory, i.e. the directory from which you invoked the node command. __dirname returns the directory name of the directory containing the JavaScript source code file.
The easiest method:
['SIGINT', 'SIGTERM', 'SIGQUIT']
.forEach(signal => process.on(signal, () => {
/** do your logic */
process.exit();
}));
I'd rather go with
/**
* Do stuff and exit the process
*/
function signalHandler() {
// do some stuff here
process.exit()
}
process.on('SIGINT', signalHandler)
process.on('SIGTERM', signalHandler)
process.on('SIGQUIT', signalHandler)
for style and clarity reasons
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With