Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exit in Node.js

Tags:

node.js

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

like image 760
700 Software Avatar asked Mar 10 '11 21:03

700 Software


People also ask

What is process exit 1 in Node JS?

The process. exit() method is used to end the process which is running at the same time with an exit code in NodeJS.

How do I exit NPM?

To stop a running npm process, press CTRL + C or close the shell window.


2 Answers

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.

like image 183
7 revs, 5 users 51% Avatar answered Sep 29 '22 18:09

7 revs, 5 users 51%


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; } 
like image 44
Dominic Avatar answered Sep 29 '22 18:09

Dominic