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
JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.