I read node.js docs. It says:
Even though the name of this function is
process.kill()
, it is really just a signal sender, as the kill system call. The signal sent may do something other than killing the target process.
console.log('current process id: ', process.pid);
process.on('SIGHUP', function() {
console.log('Got SIGHUP signal');
});
setTimeout(() => {
console.log('Exiting...');
process.exit(0); //kill process
console.log('Process id that has exited: ', process.pid); //does not output
}, 1000);
process.kill(process.pid, 'SIGHUP'); //does not kill process
console.log('Id of the process exiting: ', process.pid); //so this output normally
output:
current process id: 64520
Id of the process exiting: 64520
Got SIGHUP signal
Exiting...
It seems process.exit(0)
is the one which kills node.js
process.
It all depends on the situation that you're in. Like Gospal Joshi said process.exit([code])
is useful to end the process very quickly. But in other cases you may want to pass a signal to that process before shutdown for cleanup/graceful shutdown. For example if you are listening to signal events such as:
process.on('SIGINT', () => {
//do something
}
it allows you to run cleanup or gracefully shutdown the process vs exiting instantly without doing anything.
Also, note that Node.js establishes signal handlers for SIGINT and SIGTERM and Node.js processes will not terminate immediately due to receipt of those signals. Rather, Node.js will perform a sequence of cleanup actions and then will re-raise the handled signal
- Node Documentation
Use process.exit()
, It ends the process with the specified code. Calling process.exit()
will force the process to exit as quickly as possible even if there are still asynchronous operations pending
Syntax:
process.exit([code])
Links:
process.kill(pid, [ code ])
shines on concurrent applications with multiple processes (since you can just plug in the pid of the process you wish to kill and it does it).
process.exit()
is sufficient and most common if you dont have a usecase that requires killing any other process than the main node process.
Personally, I recommend you to use process.exit()
unless you really have to kill another process (pid different than process.pid
)
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