How to exit in Node.js
Call the global process
object's exit
method:
process.exit()
From the docs:
process.exit([exitcode])
Ends the process with the specified
code
. If omitted, exit with a 'success' code0
.To exit with a 'failure' code:
process.exit(1);
The shell that executed node should see the exit code as
1
.
If you're in a Unix terminal or Windows command line and want to exit the Node REPL, either...
- Press Ctrl + C twice, or
- type
.exit
and press Enter, or - press Ctrl + D at the start of a line (Unix only)
Just a note that using process.exit([number])
is not recommended practice.
Calling
process.exit()
will force the process to exit as quickly as possible even if there are still asynchronous operations pending that have not yet completed fully, including I/O operations toprocess.stdout
andprocess.stderr
.In most situations, it is not actually necessary to call
process.exit()
explicitly. The Node.js process will exit on its own if there is no additional work pending in the event loop. Theprocess.exitCode
property can be set to tell the process which exit code to use when the process exits gracefully.For instance, the following example illustrates a misuse of the
process.exit()
method that could lead to data printed tostdout
being truncated and lost:// This is an example of what *not* to do: if (someConditionNotMet()) { printUsageToStdout(); process.exit(1); }
The reason this is problematic is because writes to
process.stdout
in Node.js are sometimes asynchronous and may occur over multiple ticks of the Node.js event loop. Callingprocess.exit()
, however, forces the process to exit before those additional writes tostdout
can be performed.Rather than calling
process.exit()
directly, the code should set theprocess.exitCode
and allow the process to exit naturally by avoiding scheduling any additional work for the event loop:// How to properly set the exit code while letting // the process exit gracefully. if (someConditionNotMet()) { printUsageToStdout(); process.exitCode = 1; }
From the official nodejs.org documentation:
process.exit(code)
Ends the process with the specified code. If omitted, exit uses the 'success' code 0.
To exit with a 'failure' code:
process.exit(1);