如何在 Node.js 中退出

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5266152/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 13:56:03  来源:igfitidea点击:

How to exit in Node.js

node.js

提问by Bryan Field

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

退出的命令是什么?(即终止 Node.js 进程)

回答by Pero P.

Call the global processobject's exitmethod:

调用全局process对象的exit方法:

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.

process.exit([代码])

以指定的 结束进程code。如果省略,则退出使用“成功”代码0

以“失败”代码退出:

process.exit(1);

执行 node 的 shell 应将退出代码视为1.

回答by Dominic

Just a notethat using process.exit([number])is not recommendedpractice.

只是一个音符,使用process.exit([number])不推荐的做法。

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 misuseof 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;
}

调用 process.exit() 将强制进程尽快退出,即使仍有未完成的异步操作挂起,包括对 process.stdout 和 process.stderr 的 I/O 操作。

在大多数情况下,实际上没有必要显式调用 process.exit()。如果事件循环中没有其他待处理的工作,Node.js 进程将自行退出。可以设置 process.exitCode 属性来告诉进程在进程正常退出时使用哪个退出代码。

例如,以下示例说明了process.exit() 方法的滥用可能导致打印到 stdout 的数据被截断和丢失:

// This is an example of what *not* to do:
if (someConditionNotMet()) {
  printUsageToStdout();
  process.exit(1);
}

这是有问题的原因是因为在 Node.js 中写入 process.stdout 有时是异步的,并且可能发生在 Node.js 事件循环的多个滴答上。但是,调用 process.exit() 会强制进程退出,然后才能执行对 stdout 的额外写入。

代码不应直接调用 process.exit(),而是应设置 process.exitCode 并通过避免为事件循环安排任何额外工作来允许进程自然退出:

// How to properly set the exit code while letting
// the process exit gracefully.
if (someConditionNotMet()) {
  printUsageToStdout();  
  process.exitCode = 1;
}

回答by alienhard

From the official nodejs.orgdocumentation:

来自官方nodejs.org文档:

process.exit(code)

Ends the process with the specified code. If omitted, exit uses the 'success' code 0.

用指定的代码结束进程。如果省略,则退出使用“成功”代码 0。

To exit with a 'failure' code:

以“失败”代码退出:

process.exit(1);

回答by Mohsen

If you're in a Unix terminal or Windows command line and want to exit the Node REPL, either...

如果您在 Unix 终端或 Windows 命令行中并想退出 Node REPL,要么...

  • Press Ctrl+ Ctwice, or
  • type .exitand press Enter, or
  • press Ctrl+ Dat the start of a line (Unix only)
  • Ctrl+C两次,或
  • 键入.exit并按 Enter,或
  • 在行首按Ctrl+ D(仅限 Unix)

回答by Mike M. Lin

From the command line, .exitis what you want:

从命令行,.exit就是你想要的:

$ node
> .exit
$

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

它记录在REPL 文档中。REPL(Read-Eval-Print-Loop)就是 Node 命令行的名称。

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

在普通程序中,使用process.exit([code]).

回答by teq

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:

这取决于您愿意退出 node.js 进程的原因,但无论如何process.exit()最后一个要考虑的选项。来自文档的引用:

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.stdoutand 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.exitCodeproperty can be set to tell the process which exit code to use when the process exits gracefully.

需要注意的是,调用process.exit()将强制进程尽快退出,即使仍有尚未完全完成的异步操作挂起,包括对process.stdout和 的I/O 操作process.stderr

在大多数情况下,实际上并不需要process.exit()显式调用 。如果事件循环中没有其他待处理的工作,Node.js 进程将自行退出。该 process.exitCode属性可以设置为告诉进程在进程正常退出时使用哪个退出代码。

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

让我们介绍一下您可能愿意退出 node.js 进程的可能原因以及您应该避免的原因process.exit()

Case 1 - Execution complete (command line script)

案例 1 - 执行完成(命令行脚本)

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.exitCodeto return any result to calling process.

如果脚本已经结束并且节点解释器没有退出,则表明一些异步操作仍在挂起。此时强制终止进程是错误的process.exit()。最好尝试了解阻止您的脚本以预期方式退出的原因。当您解决此问题时,您可以使用process.exitCode将任何结果返回给调用进程。

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

情况 2 - 由于外部信号(SIGINT/SIGTERM/other)而终止

For example, if you're willing to gracefully shut down an expressapp. 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():

例如,如果您愿意优雅地关闭Express应用程序。与命令行脚本不同,express app 会无限运行,等待新的请求。process.exit()在这里将是一个糟糕的选择,因为它会中断管道中的所有请求。其中一些可能是非幂等的(更新、删除)。客户端永远不会知道这些请求是否在服务器端完成,这可能是客户端和服务器之间数据不一致的原因。唯一好的解决方案是告诉 http 服务器停止接受新请求并等待挂起的请求完成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.

如果它仍然没有退出 - 请参阅案例 1。

Case 3 - Internal error

案例 3 - 内部错误

It's always better to throwan 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.

throw出错总是更好,你会得到一个格式很好的堆栈跟踪和错误消息。上层代码总是可以决定他们是否可以处理错误 ( catch) 或让它使进程崩溃。另一方面,process.exit(1)将静默终止进程,并且没有机会从中恢复。这可能是 的唯一“好处” process.exit(),您可以确定该过程将被终止。

回答by Siva Prakash

REPL(Command Line)

REPL(命令行)

  • Press ctrl + ctwice

  • Type .exitand press enter

  • ctrl + c两次

  • 键入.exit,然后按Enter

Script File

脚本文件

process.exit(code)

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

当没有更多异步操作挂起时,节点通常以代码 0退出。

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.

process.exit(1)应该用于以失败代码退出。这将允许我们推断该节点没有正常关闭并被迫关闭。

There are other exit codes like

还有其他退出代码,如

3 - Internal JavaScript Parse Error ( very very rare)

3 - 内部 JavaScript 解析错误(非常非常罕见)

5 - Fatal error in v8 javascript engine

5 - v8 javascript 引擎中的致命错误

9 - Invalid argument

9 - 无效参数

For full list see node exit codes

有关完整列表,请参阅节点退出代码

回答by Stephen Quan

I have an application which I wanted to:

我有一个应用程序,我想:

  1. Send an email to the user
  2. Exit with an error code
  1. 向用户发送电子邮件
  2. 以错误代码退出

I had to hook process.exit(code)to an exitevent handler, or else the mail will not be sent since calling process.exit(code)directly kills asynchronous events.

我必须挂钩process.exit(code)到一个exit事件处理程序,否则邮件将不会被发送,因为process.exit(code)直接调用会杀死异步事件。

#!/usr/bin/nodejs
var mailer = require('nodemailer');
var transport = mailer.createTransport();
mail = {
  to: 'Dave Bowman',
  from: 'HAL 9000',
  subject: 'Sorry Dave',
  html: 'Im sorry, Dave. Im afraid I cant do <B>THAT</B>.'
}
transport.sendMail(mail);
//process.exit(1);
process.on('exit', function() { process.exit(1); });

回答by MANN

As @Dominic pointed out, throwing an uncaught erroris better practice instead of calling process.exit([code]):
process.exitCode = 1; throw new Error("my module xx condition failed");

正如@Dominic 指出的,抛出未捕获的错误是更好的做法,而不是调用process.exit([code])
process.exitCode = 1; throw new Error("my module xx condition failed");

回答by Denis Lisitskiy

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