TIL How to exit out of a node script
POSTED ON:
TAGS: node errorcodes
If you write a node script, you can terminate it by Ctrl+C, or forcing a quit within the script.
The process core module provides a handy method that allows you to programmatically exit from a Node.js program: process.exit()
.
When Node.js runs this line, the process is immediately forced to terminate.
This means that any callback that's pending, any network request still being sent, any filesystem access, or processes writing to stdout or stderr - all is going to be ungracefully terminated right away.
via https://nodejs.dev/learn/how-to-exit-from-a-nodejs-program
(If you're running a server or something that needs to gracefully exit, do the process.kill(process.pid, 'SIGTERM')
instead. I don't know how that works yet. Future TIL? :-D )
(async () => {
try {
// ...
} catch (e) {
// eslint-disable-next-line no-console
console.log(e.message);
// switches it to 1, or whatever you want
process.exitCode = 1
}
// automatically quits
// OR process.exit(int number);
process.exit();
})();
Related TILs
Tagged: node