Home > Web Front-end > JS Tutorial > Detailed explanation of several methods to actively terminate the Node.js process

Detailed explanation of several methods to actively terminate the Node.js process

青灯夜游
Release: 2021-04-27 09:14:31
forward
6021 people have browsed it

This article will introduce to you some methods to actively trigger Node process termination. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

Detailed explanation of several methods to actively terminate the Node.js process

#There are several reasons why a Node.js process may terminate. Some of these are avoidable, such as when an error is thrown, while others are unpreventable, such as out of memory. The global process is an Event Emitter instance that emits an exit event when execution exits normally. Program code can then perform final synchronized cleanup work by listening to this event.

Related recommendations: "nodejs Tutorial"

The following are some methods that can actively trigger process termination:

Operation Example
Manual process exit process.exit(1)
Uncaught exception throw new Error()
Unfulfilled promise Promise.reject()
Ignored error event EventEmitter#emit('error')
Unhandled signal $ kill <PROCESS_ID>

Many of them are triggered accidentally, such as uncaught errors or unhandled promises, but some of them are created to directly terminate the process.

Process Exit

Using process.exit(code) is the most direct way to terminate the process. This is useful when you know your process has reached the end of its life cycle. code The value is optional, the default value is 0, and the maximum value can be set to 255. 0 indicates that the process ran successfully, and any non-zero number indicates that a problem occurred. These values ​​can be used by many different external tools. For example, when a test suite is run, a non-zero value indicates that the test failed.

When calling process.exit() directly, no implicit text is written to the console. If you write code that calls this method with an error representation, your code should output the error to the user to help them solve the problem. For example, run the following code:

$ node -e "process.exit(42)"
$ echo $?
Copy after login

In this case, the single-line Node.js program will not output any information, although the shell program does print the exit status. When encountering such a process exit, the user will not be able to understand what happened. So please refer to the following code that will be executed when the program is configured incorrectly:

function checkConfig(config) {
  if (!config.host) {
    console.error("Configuration is missing &#39;host&#39; parameter!");
    process.exit(1);
  }
}
Copy after login

In this case, the user will not clearly understand what happened. They run the program, it prints errors to the console, and they are able to correct the problem.

process.exit() The method is very powerful. Although it has its own uses in program code, it should never be introduced into a reusable library. If an error does occur in the library, this error should be thrown so that the program can decide how to handle it.

exceprion, rejection and Error issued

While process.exit() is useful, for runtime errors you need to use something else tool. For example, when a program is handling an HTTP request, generally an error should not terminate the process, but only return an error response. It is also useful to know where the error occurred, which is where the Error object should be thrown. Instances of the

Error class contain useful metadata about what caused the error, such as stack trace information and message strings. It is common practice to extend your own error class from Error. Instantiating Error alone won't have many side effects and must be thrown if an error occurs.

Error will be thrown when the throw keyword is used or when certain logic errors occur. When this happens, the current stack will be "unrolled," meaning every function will exit until a calling function wraps the call in a try/catch statement. After this statement is encountered, the catch branch is called. If the error is not contained in a try/catch, the error is considered uncaught.

Although you should technically use the throw keyword with Error, such as throw new Error('foo') Talk, you can throw anything. Once something is thrown, it is considered an exception. It's important to throw Error instances because code that catches these errors will most likely expect an error attribute.

Node.js Another pattern commonly used in internal libraries is to provide a .code property which is a string value that changes between releases Should be consistent. For example, the wrong .code value is ERR_INVALID_URI, even though the human-readable .message attribute may change, this code The value should not be changed either.

Sadly, a more common pattern for distinguishing errors is to check the .message property, which is usually dynamic because spelling errors may need to be corrected. This method is very risky and error-prone. There is no perfect solution in the Node.js ecosystem to distinguish bugs in all libraries.

When an uncaught error is thrown, a stack trace will be printed in the console and the process will terminate with exit status 1. Here is an example of such an exception:

/tmp/foo.js:1
throw new TypeError(&#39;invalid foo&#39;);
^
Error: invalid foo
    at Object.<anonymous> (/tmp/foo.js:2:11)
    ... TRUNCATED ...
    at internal/main/run_main_module.js:17:47
Copy after login

The stack trace snippet above indicates that the error occurred at line 2, column 11 of the file named foo.js.

The global process is an event emitter that can intercept uncaught errors by listening to the uncaughtException event. Here's an example of using it, intercepting errors before exiting to send an asynchronous message:

const logger = require(&#39;./lib/logger.js&#39;);
process.on(&#39;uncaughtException&#39;, (error) => {
  logger.send("An uncaught exception has occured", error, () => {
    console.error(error);
    process.exit(1);
  });
});
Copy after login

Promise rejection is very similar to throwing an error. A Promise can be rejected if the reject() method in the Promise is called, or if an error is raised in an asynchronous function. In this regard, the following two examples are roughly the same:

Promise.reject(new Error(&#39;oh no&#39;));

(async () => {
  throw new Error(&#39;oh no&#39;);
})();
Copy after login

This is the message output to the console:

(node:52298) UnhandledPromiseRejectionWarning: Error: oh no
    at Object.<anonymous> (/tmp/reject.js:1:16)
    ... TRUNCATED ...
    at internal/main/run_main_module.js:17:47
(node:52298) UnhandledPromiseRejectionWarning: Unhandled promise
  rejection. This error originated either by throwing inside of an
  async function without a catch block, or by rejecting a promise
  which was not handled with .catch().
Copy after login

Unlike uncaught exceptions, starting with Node.js v14, these rejections Will not crash the process. In a future version of Node.js, this will crash the current process. You can also intercept the event when these unhandled rejections occur, listening for another event on the process object:

process.on(&#39;unhandledRejection&#39;, (reason, promise) => {});
Copy after login

事件发射器是 Node.js 中的常见模式,许多对象实例都从这个基类扩展而来,并在库和程序中使用。它们非常欢迎,值得和 error 与 rejection 放在一起讨论。

当事件发射器发出没有侦听器的 error 事件时,将会抛出所发出的参数。然后将抛出出一个错误并导致进程退出:

events.js:306
    throw err; // Unhandled &#39;error&#39; event
    ^
Error [ERR_UNHANDLED_ERROR]: Unhandled error. (undefined)
    at EventEmitter.emit (events.js:304:17)
    at Object.<anonymous> (/tmp/foo.js:1:40)
    ... TRUNCATED ...
    at internal/main/run_main_module.js:17:47 {
  code: &#39;ERR_UNHANDLED_ERROR&#39;,
  context: undefined
}
Copy after login

确保在你使用的事件发射器实例中侦听 error 事件,以便你的程序可以正常处理事件而不会崩溃。

信号

信号是操作系统提供的机制,用于把用数字表示的消息从一个程序发送到另一个程序。这些数字通常用等价的常量字符串来表示。例如,信号 SIGKILL 代表数字信号 9。信号可以有不同的用途,但通常用于终止程序。

不同的操作系统可以定义不同的信号,但是下面列表中的信号一般是通用的:

名称编号可处理Node.js 默认信号用途
SIGHUP1终止父终端已关闭
SIGINT2终止终端试图中断,按下 Ctrl + C
SIGQUIT3终止终端试图退出,按下 Ctrl + D
SIGKILL9终止进程被强行杀死
SIGUSR110启动调试器用户定义的信号1
SIGUSR212终止用户定义的信号2
SIGTERM12终止代表优雅的终止
SIGSTOP19终止进程被强行停止

如果程序可以选择实现信号处理程序,则 Handleable 一列则为。为的两个信号无法处理。 Node.js 默认 这一列告诉你在收到信号时,Node.js 程序的默认操作是什么。最后一个信号用途指出了信号对应的作用。

在 Node.js 程序中处理这些信号可以通过侦听 process 对象上的更多事件来完成:

#!/usr/bin/env node
console.log(`Process ID: ${process.pid}`);
process.on(&#39;SIGHUP&#39;, () => console.log(&#39;Received: SIGHUP&#39;));
process.on(&#39;SIGINT&#39;, () => console.log(&#39;Received: SIGINT&#39;));
setTimeout(() => {}, 5 * 60 * 1000); // keep process alive
Copy after login

在终端窗口中运行这个程序,然后按 Ctrl + C,这个进程不会被终止。它将会声明已接收到 SIGINT 信号。切换到另一个终端窗口,并根据输出的进程 ID 值执行以下命令:

$ kill -s SIGHUP <PROCESS_ID>
Copy after login

这演示了一个程序怎样向另一个程序发送信号,并且在第一个终端中运行的 Node.js 程序中输出它所接收到的 SIGHUP 信号。

你可能已经猜到了,Node.js 也能把命令发送到其他程序。可以用下面的命令以把信号从临时的 Node.js 进程发送到你现有的进程:

$ node -e "process.kill(<PROCESS_ID>, &#39;SIGHUP&#39;)"
Copy after login

这还会在你的第一个程序中显示 SIGHUP 消息。现在,如果你想终止第一个进程,要运行下面的命令向其发送不能处理的 SIGKILL 信号:

$ kill -9 <PROCESS_ID>
Copy after login

这时程序应该结束。

这些信号在 Node.js 程序中经常用于处理正常的关闭事件。例如,当 Kubernetes Pod 终止时,它将向程序发送 SIGTERM 信号,之后启动 30 秒计时器。然后程序可以在这 30 秒内正常关闭自己,关闭连接并保存数据。如果该进程在此计时器后仍保持活动状态,则 Kubernetes 将向其发送一个 SIGKILL

更多编程相关知识,请访问:编程视频!!

The above is the detailed content of Detailed explanation of several methods to actively terminate the Node.js process. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template