search
HomeWeb Front-endJS TutorialDetailed explanation of several methods to actively terminate the Node.js process

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></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 $?

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

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

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

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

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().

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) => {});

事件发射器是 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
}

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

信号

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

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

名称 编号 可处理 Node.js 默认 信号用途
SIGHUP 1 终止 父终端已关闭
SIGINT 2 终止 终端试图中断,按下 Ctrl + C
SIGQUIT 3 终止 终端试图退出,按下 Ctrl + D
SIGKILL 9 终止 进程被强行杀死
SIGUSR1 10 启动调试器 用户定义的信号1
SIGUSR2 12 终止 用户定义的信号2
SIGTERM 12 终止 代表优雅的终止
SIGSTOP 19 终止 进程被强行停止

如果程序可以选择实现信号处理程序,则 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

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

$ kill -s SIGHUP <PROCESS_ID>

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

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

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

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

$ kill -9 <PROCESS_ID>

这时程序应该结束。

这些信号在 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!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
5个常见的JavaScript内存错误5个常见的JavaScript内存错误Aug 25, 2022 am 10:27 AM

JavaScript 不提供任何内存管理操作。相反,内存由 JavaScript VM 通过内存回收过程管理,该过程称为垃圾收集。

巧用CSS实现各种奇形怪状按钮(附代码)巧用CSS实现各种奇形怪状按钮(附代码)Jul 19, 2022 am 11:28 AM

本篇文章带大家看看怎么使用 CSS 轻松实现高频出现的各类奇形怪状按钮,希望对大家有所帮助!

Node.js 19正式发布,聊聊它的 6 大特性!Node.js 19正式发布,聊聊它的 6 大特性!Nov 16, 2022 pm 08:34 PM

Node 19已正式发布,下面本篇文章就来带大家详解了解一下Node.js 19的 6 大特性,希望对大家有所帮助!

实战:vscode中开发一个支持vue文件跳转到定义的插件实战:vscode中开发一个支持vue文件跳转到定义的插件Nov 16, 2022 pm 08:43 PM

vscode自身是支持vue文件组件跳转到定义的,但是支持的力度是非常弱的。我们在vue-cli的配置的下,可以写很多灵活的用法,这样可以提升我们的生产效率。但是正是这些灵活的写法,导致了vscode自身提供的功能无法支持跳转到文件定义。为了兼容这些灵活的写法,提高工作效率,所以写了一个vscode支持vue文件跳转到定义的插件。

浅析Vue3动态组件怎么进行异常处理浅析Vue3动态组件怎么进行异常处理Dec 02, 2022 pm 09:11 PM

Vue3动态组件怎么进行异常处理?下面本篇文章带大家聊聊Vue3 动态组件异常处理的方法,希望对大家有所帮助!

聊聊如何选择一个最好的Node.js Docker镜像?聊聊如何选择一个最好的Node.js Docker镜像?Dec 13, 2022 pm 08:00 PM

选择一个Node​的Docker镜像看起来像是一件小事,但是镜像的大小和潜在漏洞可能会对你的CI/CD流程和安全造成重大的影响。那我们如何选择一个最好Node.js Docker镜像呢?

聊聊Node.js中的 GC (垃圾回收)机制聊聊Node.js中的 GC (垃圾回收)机制Nov 29, 2022 pm 08:44 PM

Node.js 是如何做 GC (垃圾回收)的?下面本篇文章就来带大家了解一下。

【6大类】实用的前端处理文件的工具库,快来收藏吧!【6大类】实用的前端处理文件的工具库,快来收藏吧!Jul 15, 2022 pm 02:58 PM

本篇文章给大家整理和分享几个前端文件处理相关的实用工具库,共分成6大类一一介绍给大家,希望对大家有所帮助。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download

Atom editor mac version download

The most popular open source editor