How to exit in Node.js – Dev

The best answers to the question “How to exit in Node.js” in the category Dev.

QUESTION:

What is the command that is used to exit? (i.e terminate the Node.js process)

ANSWER:

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 to
process.stdout and process.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. The
process.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 to stdout 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. Calling process.exit(), however, forces the
process to exit before those additional writes to stdout can be
performed.

Rather than calling process.exit() directly, the code should set the
process.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;
}

ANSWER:

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 uses the ‘success’ code 0.

To exit with a ‘failure’ code:

process.exit(1);

The shell that executed node should see the exit code as 1.

ANSWER:

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)

ANSWER:

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);