How to Exit in Node.js - Scripts or Processes
Exiting a Node.js application can be done using the process.exit()
method.
The process.exit()
method terminates the Node.js process immediately. You can optionally pass an exit code to indicate whether the program exited due to an error or finished successfully.
How to
Exiting Normally
To exit with a success code (indicating that the program was completed without errors), use:
process.exit();
Or explicitly pass a success exit code 0
:
process.exit(0); // Zero signals a success
Exiting Due to an Error
To indicate that your program is exiting because of an error, pass an exit code other than 0
. A common convention is to use 1
:
process.exit(1);
And an Example
As always, I think it's easiest when you see it in action:
const fs = require('fs'); fs.writeFile('hacker.txt', 'Hello, world!', (err) => { if (err) { console.error('Failed to write file:', err); process.exit(1); // Exit with an error code } console.log('File written successfully.'); // No need to call process.exit() here as the program will exit on its own // when there are no more asynchronous operations pending. });
This example demonstrates writing to a file asynchronously. If an error occurs, it logs it and exits with a status code 1. If the operation is successful, it logs a success message.
Some Notes:
Before calling
process.exit()
, you should clean up any resources your application uses, database connections, or network requests. This ensures that you don't leave resources hanging or data in an inconsistent state.Use Exit Codes! Exit codes are a way to communicate the outcome of your script to the operating system or to other scripts that might be calling your script. By convention, a code of 0 means success, and any code higher than 0 indicates an error.