如何在 Node.js 中退出

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

转载于:https://stackoverflow.com/questions/5266152/how-to-exit-in-node-js

16个回答

Call the global process object's exit method:

process.exit()

From the docs:

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

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

csdnceshi71
Memor.の Please note that process.exit() is not recommended, as described in this answer below.
接近 3 年之前 回复
csdnceshi77
狐狸.fox And PHP is a general purpose language. No need to run it with mod_php or use Apache. You can reimplement an httpd in PHP like node does if you really want or use a more sane/standardized approach like FastCGI just like you can in node.
大约 4 年之前 回复
csdnceshi52
妄徒之命 exit isn't misleading at all. You are confused about how Node works. Think of Node as the server itself. It isn't just fired up as needed, like PHP is within a web server like Apache. Node doesn't even have to have anything to do with web servers at all! It's just a host for some JavaScript, with some nifty built-in libraries for doing useful things.
大约 8 年之前 回复
csdnceshi51
旧行李 Just want to add something. If you are handling a request, you should also end() the request as well. Otherwise, it'll just hang.
8 年多之前 回复

From the command line, .exit is what you want:

$ node
> .exit
$

It's documented in the REPL docs. REPL (Read-Eval-Print-Loop) is what the Node command line is called.

From a normal program, use process.exit([code]).

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)
csdnceshi71
Memor.の For the node REPL, Ctrl+D to exit is a standard behavior, so it also works on Windows.
接近 3 年之前 回复
csdnceshi57
perhaps? Note that, beyond Node, the Ctrl+D shortcut on Mac or Linux works on almost all shells and REPLs you'll ever encounter, including Unix shells like Bash, the shells for databases like MySQL and PostgreSQL, and the REPLs for programming languages like Python, PHP, and Ruby. It is the only method of exiting shells I ever use.
5 年多之前 回复

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);
csdnceshi69
YaoRaoLov the code is not for you, it's for whatever ran your code. For example, if you create an exit_0.js with process.exit(0); and run it with node exit_0.js && echo 'success' it will say "success". If you create exit_1.js with process.exit(1); and run node exit_1.js && echo 'success' it will not say "success" since your process exited with a non-zero (which indicates a "failure" or "abnormal exit" to the shell). In addition, you will see different values in $? if you run node exit_1.js vs node exit_0.js (you can check by doing node exit_1.js and then doing echo $?).
大约 6 年之前 回复
csdnceshi80
胖鸭 You are correct -- Code is just a variable, and in this case used to indicate what the parameter is. So .exit(0) does everything the example does.
6 年多之前 回复
weixin_41568134
MAO-EYE A better idea is just process.exit() with no parameter as code defaults to 0
6 年多之前 回复
csdnceshi52
妄徒之命 So funny, I tried with all exit, quit, end, stop but none of them worked, and the correct one is yours :D. Thanks.
大约 7 年之前 回复
weixin_41568126
乱世@小熊 I tried in Cloud9 IDE. It just works! Thank you
7 年多之前 回复
weixin_41568196
撒拉嘿哟木头 You can always yourself determine, depending on that you don't override an already existing error code, where the program exited and with which error code.
7 年多之前 回复
weixin_41568174
from.. Is it true that if you're exiting, you probably don't care about the value of code?
7 年多之前 回复
csdnceshi60
℡Wang Yan yes, or more precisely code = 0; process.exit(code);
7 年多之前 回复
weixin_41568174
from.. Could process.exit(code=0) be rewritten as code = 0; process.exit(0)?
7 年多之前 回复

Just a note that using process.exit([number]) is not recommended practice.

The reason this is problematic is because writes to process.stdout in Node.js are non-blocking 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:

If you can you should set the exit code and allow Node to exit gracefully:

process.exitCode = 1;
csdnceshi73
喵-见缝插针 So you are saying that if you don't care about stdout you can merrily use process.exit()?
接近 2 年之前 回复
weixin_41568174
from.. Actually this quote is from Jun 2016 and the docs still haven't changed for v9 :)
2 年多之前 回复
csdnceshi71
Memor.の Please be aware that referenced documentation is for version 9. This may not equally apply for previous versions of NodeJS.
2 年多之前 回复
weixin_41568174
from.. Hence why the answer is prefixed with "Just a note"
2 年多之前 回复
weixin_41568126
乱世@小熊 This is not the best answer by any stretch because it doesn't answer the question. Instead, it gives best practices on how to develop code flow for a nodejs program.
接近 3 年之前 回复
csdnceshi55
~Onlooker There are many uses cases for immediate process and pending event termination. That is exactly what process.exit() is intended for.
接近 3 年之前 回复
csdnceshi52
妄徒之命 If you fork a child process you MUST child.disconnect(); for process.exitCode=0 (or 1) to take affect. Not disconnecting will cause your program to hang. nodejs.org/dist/latest-v6.x/docs/api/…
大约 3 年之前 回复
weixin_41568174
from.. Then I'd imagine something is keeping it open - if you do echo "console.log('hello')" >> ./test.js && node test.js you should see it print hello and then exit
3 年多之前 回复
weixin_41568134
MAO-EYE I used this answer and found that my process never actually exited. Had to ctrl-C it.
3 年多之前 回复
csdnceshi67
bug^君 Agreed, this should have more upvotes! I had a node script that was kicking off multiple child processes via shelljs.exec and I wanted my overall script to return with an error exit code if any of the child processes failed. process.exitCode = 1 worked great in the exec callbacks (whereas simply calling process.exit(1) in there would exit the main script before all child processes finished!)
接近 4 年之前 回复
csdnceshi57
perhaps? This is the best answer, by far. Other answers might not allow node to properly process pending events before exit, very sad :(
接近 4 年之前 回复

To exit

let exitCode = 1;
process.exit(exitCode)

Useful exit codes

1 - Catchall for general errors
2 - Misuse of shell builtins (according to Bash documentation)
126 - Command invoked cannot execute
127 - “command not found”
128 - Invalid argument to exit
128+n - Fatal error signal “n”
130 - Script terminated by Control-C
255\* - Exit status out of range
csdnceshi65
larry*wei Consider updating your answer, nodejs.org/api/process.html#process_process_exit_code
大约 3 年之前 回复

It depends on the reason why you're willing to exit node.js process, but in any case process.exit() is the last option to consider. A quote from documentation:

It is important to note that 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 it's 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.

Let’s cover possible reasons why you might be willing to exit node.js process and why you should avoid process.exit():

Case 1 - Execution complete (command line script)

If script has reached its end and node interpreter doesn't exit, it indicates that some async operations are still pending. It’s wrong to force process termination with process.exit() at this point. It’s better to try to understand what is holding your script from exiting in expected way. And when you settle this, you can use process.exitCode to return any result to calling process.

Case 2 - Termination because of external signal (SIGINT/SIGTERM/other)

For example, if you’re willing to gracefully shut down an express app. Unlike command line script, express app keeps running infinitely, waiting for new requests. process.exit() will be a bad option here because it’s going to interrupt all requests which are in pipeline. And some of them might be non-idempotent (UPDATE, DELETE). Client will never know if those requests are completed or not on server side and it might be the reason of data inconsistency between client and server. The only good solution is to tell http server to stop accepting new requests and wait for pending ones to finish with server.close():

var express = require('express');
var app = express();
var server = app.listen(80);

process.on( 'SIGTERM', function () {
   server.close(function () {
     console.log("Finished all requests");
   });
});

If it still doesn't exit - see Case 1.

Case 3 - Internal error

It's always better to throw an error, you’ll get a nicely formatted stack trace and error message. Upper levels of code can always decide if they can handle error (catch) or let it crash the process. On the other side, process.exit(1) will terminate process silently and there will be no chance to recover from this. It might be the only “benefit” of process.exit(), you can be sure that process will be terminated.

weixin_41568127
?yb? If one has a bunch of code which is supposed to execute continuously until a shutdown request is received, is there any nice convention for registering events that would allow subscriptions to be abandoned in response to a shutdown request, without that requiring the code using the events or the code requesting the shutdown have specific knowledge about each other? Unfortunately, the only way I can think of to kinda-sorta implement that would be to require that any piece of code that registers an event also create a wrapper which includes a closure to unregister it.
2 年多之前 回复
weixin_41568134
MAO-EYE Amazing response. Process.exit() looks like major overkill for most applications. I was looking for an equivalent to php's die() function... more like: throw new Error('die msg')
3 年多之前 回复

REPL(Command Line)

  • Press ctrl + c twice

  • Type .exit and press enter

Script File

process.exit(code)

Node normally exits with code 0 when no more async operations are pending.

process.exit(1) should be used to exit with a failure code.This will allow us to infer that node didn't close gracefully and was forced to close.

There are other exit codes like

3 - Internal JavaScript Parse Error ( very very rare)

5 - Fatal error in v8 javascript engine

9 - Invalid argument

For full list see node exit codes

From code you can use process.exit([errorcode]) where [errorcode] is an optional integer (0 is the default to indicate success).

If you're using the Read Eval Print Loop (REPL), you can use Ctrl + D, or type .exit

Alternatively, on Windows or Linux you can use Ctrl + C, Ctrl + C

On Mac the command is Ctrl + Z, Ctrl + Z

weixin_41568110
七度&光 Two control c's works on the mac, too, at least on mine with node --version v0.10.18
大约 6 年之前 回复

Command Line

Press CTRL + C twice

OR

Type .exit and press enter

Script File

process.exit(code)
weixin_41568110
七度&光 How does this add anything to the answers already submitted since the question was asked in 2011?
2 年多之前 回复
共16条数据 1 尾页
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐