Node.js v22.11.0 文档


进程#

¥Process

源代码: lib/process.js

process 对象提供有关当前 Node.js 进程的信息并对其进行控制。

¥The process object provides information about, and control over, the current Node.js process.

import process from 'node:process';const process = require('node:process');

进程事件#

¥Process events

process 对象是 EventEmitter 的实例。

¥The process object is an instance of EventEmitter.

事件:'beforeExit'#

¥Event: 'beforeExit'

当 Node.js 清空其事件循环并且没有额外的工作要安排时,则会触发 'beforeExit' 事件。通常情况下,当没有工作要调度时,Node.js 进程会退出,但是注册在 'beforeExit' 事件上的监听器可以进行异步的调用,从而使 Node.js 进程继续。

¥The 'beforeExit' event is emitted when Node.js empties its event loop and has no additional work to schedule. Normally, the Node.js process will exit when there is no work scheduled, but a listener registered on the 'beforeExit' event can make asynchronous calls, and thereby cause the Node.js process to continue.

调用监听器回调函数时将 process.exitCode 的值作为唯一的参数传入。

¥The listener callback function is invoked with the value of process.exitCode passed as the only argument.

对于导致显式终止的条件,例如调用 process.exit() 或未捕获的异常,不会触发 'beforeExit' 事件。

¥The 'beforeExit' event is not emitted for conditions causing explicit termination, such as calling process.exit() or uncaught exceptions.

'beforeExit' 不应用作 'exit' 事件的替代,除非打算安排额外的工作。

¥The 'beforeExit' should not be used as an alternative to the 'exit' event unless the intention is to schedule additional work.

import process from 'node:process';

process.on('beforeExit', (code) => {
  console.log('Process beforeExit event with code: ', code);
});

process.on('exit', (code) => {
  console.log('Process exit event with code: ', code);
});

console.log('This message is displayed first.');

// Prints:
// This message is displayed first.
// Process beforeExit event with code: 0
// Process exit event with code: 0const process = require('node:process');

process.on('beforeExit', (code) => {
  console.log('Process beforeExit event with code: ', code);
});

process.on('exit', (code) => {
  console.log('Process exit event with code: ', code);
});

console.log('This message is displayed first.');

// Prints:
// This message is displayed first.
// Process beforeExit event with code: 0
// Process exit event with code: 0

事件:'disconnect'#

¥Event: 'disconnect'

如果 Node.js 进程是使用 IPC 通道生成的(请参阅 子进程集群 文档),则当 IPC 通道关闭时将触发 'disconnect' 事件。

¥If the Node.js process is spawned with an IPC channel (see the Child Process and Cluster documentation), the 'disconnect' event will be emitted when the IPC channel is closed.

事件:'exit'#

¥Event: 'exit'

当 Node.js 进程由于以下任一原因即将退出时,则会触发 'exit' 事件:

¥The 'exit' event is emitted when the Node.js process is about to exit as a result of either:

  • process.exit() 方法被显式调用;

    ¥The process.exit() method being called explicitly;

  • Node.js 事件循环不再需要执行任何额外的工作。

    ¥The Node.js event loop no longer having any additional work to perform.

此时没有办法阻止事件循环的退出,一旦所有 'exit' 监听器都运行完毕,则 Node.js 进程将终止。

¥There is no way to prevent the exiting of the event loop at this point, and once all 'exit' listeners have finished running the Node.js process will terminate.

监听器回调函数使用 process.exitCode 属性指定的退出码或传给 process.exit() 方法的 exitCode 参数调用。

¥The listener callback function is invoked with the exit code specified either by the process.exitCode property, or the exitCode argument passed to the process.exit() method.

import process from 'node:process';

process.on('exit', (code) => {
  console.log(`About to exit with code: ${code}`);
});const process = require('node:process');

process.on('exit', (code) => {
  console.log(`About to exit with code: ${code}`);
});

监听器函数必须仅执行同步操作。Node.js 进程将在调用 'exit' 事件监听器之后立即退出,从而使任何仍在事件循环中排队的其他工作被丢弃。例如,在以下示例中,超时永远不会发生:

¥Listener functions must only perform synchronous operations. The Node.js process will exit immediately after calling the 'exit' event listeners causing any additional work still queued in the event loop to be abandoned. In the following example, for instance, the timeout will never occur:

import process from 'node:process';

process.on('exit', (code) => {
  setTimeout(() => {
    console.log('This will not run');
  }, 0);
});const process = require('node:process');

process.on('exit', (code) => {
  setTimeout(() => {
    console.log('This will not run');
  }, 0);
});

事件:'message'#

¥Event: 'message'

如果 Node.js 进程是使用 IPC 通道生成的(请参阅 子进程集群 文档),则只要子进程收到父进程使用 childprocess.send() 发送的消息,就会触发 'message' 事件。

¥If the Node.js process is spawned with an IPC channel (see the Child Process and Cluster documentation), the 'message' event is emitted whenever a message sent by a parent process using childprocess.send() is received by the child process.

消息经过序列化和解析。结果消息可能与最初发送的消息不同。

¥The message goes through serialization and parsing. The resulting message might not be the same as what is originally sent.

如果在衍生进程时将 serialization 选项设置为 advanced,则 message 参数可以包含 JSON 无法表示的数据。有关详细信息,请参阅 child_process 的高级序列化

¥If the serialization option was set to advanced used when spawning the process, the message argument can contain data that JSON is not able to represent. See Advanced serialization for child_process for more details.

事件:'multipleResolves'#

¥Event: 'multipleResolves'

稳定性: 0 - 已弃用

¥Stability: 0 - Deprecated

  • type <string> 解决类型'resolve''reject' 之一。

    ¥type <string> The resolution type. One of 'resolve' or 'reject'.

  • promise <Promise> 不止一次解决或拒绝的 promise。

    ¥promise <Promise> The promise that resolved or rejected more than once.

  • value <any> 在原始解决之后解决或拒绝 promise 的值。

    ¥value <any> The value with which the promise was either resolved or rejected after the original resolve.

每当 Promise 满足以下任一条件时,就会触发 'multipleResolves' 事件:

¥The 'multipleResolves' event is emitted whenever a Promise has been either:

  • 解决了不止一次。

    ¥Resolved more than once.

  • 拒绝了不止一次。

    ¥Rejected more than once.

  • 解决后拒绝。

    ¥Rejected after resolve.

  • 拒绝后解决。

    ¥Resolved after reject.

这对于在使用 Promise 构造函数时跟踪应用中的潜在错误很有用,因为多个解决被静默吞下。但是,此事件的发生并不一定表示错误。例如,Promise.race() 可以触发 'multipleResolves' 事件。

¥This is useful for tracking potential errors in an application while using the Promise constructor, as multiple resolutions are silently swallowed. However, the occurrence of this event does not necessarily indicate an error. For example, Promise.race() can trigger a 'multipleResolves' event.

由于在上面的 Promise.race() 示例这样的情况下事件的不可靠性,它已被弃用。

¥Because of the unreliability of the event in cases like the Promise.race() example above it has been deprecated.

import process from 'node:process';

process.on('multipleResolves', (type, promise, reason) => {
  console.error(type, promise, reason);
  setImmediate(() => process.exit(1));
});

async function main() {
  try {
    return await new Promise((resolve, reject) => {
      resolve('First call');
      resolve('Swallowed resolve');
      reject(new Error('Swallowed reject'));
    });
  } catch {
    throw new Error('Failed');
  }
}

main().then(console.log);
// resolve: Promise { 'First call' } 'Swallowed resolve'
// reject: Promise { 'First call' } Error: Swallowed reject
//     at Promise (*)
//     at new Promise (<anonymous>)
//     at main (*)
// First callconst process = require('node:process');

process.on('multipleResolves', (type, promise, reason) => {
  console.error(type, promise, reason);
  setImmediate(() => process.exit(1));
});

async function main() {
  try {
    return await new Promise((resolve, reject) => {
      resolve('First call');
      resolve('Swallowed resolve');
      reject(new Error('Swallowed reject'));
    });
  } catch {
    throw new Error('Failed');
  }
}

main().then(console.log);
// resolve: Promise { 'First call' } 'Swallowed resolve'
// reject: Promise { 'First call' } Error: Swallowed reject
//     at Promise (*)
//     at new Promise (<anonymous>)
//     at main (*)
// First call

事件:'rejectionHandled'#

¥Event: 'rejectionHandled'

  • promise <Promise> 最近处理的 promise。

    ¥promise <Promise> The late handled promise.

每当 Promise 被拒绝并且错误句柄被附加到它(例如使用 promise.catch())晚于一轮 Node.js 事件循环时,则 'rejectionHandled' 事件就会触发。

¥The 'rejectionHandled' event is emitted whenever a Promise has been rejected and an error handler was attached to it (using promise.catch(), for example) later than one turn of the Node.js event loop.

Promise 对象会在 'unhandledRejection' 事件中先处理,但在处理过程中获得了拒绝句柄。

¥The Promise object would have previously been emitted in an 'unhandledRejection' event, but during the course of processing gained a rejection handler.

对于 Promise 链,没有始终可以处理拒绝的顶层概念。由于本质上是异步的,Promise 拒绝可以在未来的某个时间点处理,可能比触发 'unhandledRejection' 事件所需的事件循环轮询要晚得多。

¥There is no notion of a top level for a Promise chain at which rejections can always be handled. Being inherently asynchronous in nature, a Promise rejection can be handled at a future point in time, possibly much later than the event loop turn it takes for the 'unhandledRejection' event to be emitted.

另一种表述方式是,与同步代码中未处理的异常列表不断增长不同,promise 中未处理的拒绝列表可能会不断增长和缩小。

¥Another way of stating this is that, unlike in synchronous code where there is an ever-growing list of unhandled exceptions, with Promises there can be a growing-and-shrinking list of unhandled rejections.

在同步代码中,当未处理的异常列表增长时,会触发 'uncaughtException' 事件。

¥In synchronous code, the 'uncaughtException' event is emitted when the list of unhandled exceptions grows.

在异步代码中,当未处理的拒绝列表增长时,会触发 'unhandledRejection' 事件,当未处理的拒绝列表缩小时,会触发 'rejectionHandled' 事件。

¥In asynchronous code, the 'unhandledRejection' event is emitted when the list of unhandled rejections grows, and the 'rejectionHandled' event is emitted when the list of unhandled rejections shrinks.

import process from 'node:process';

const unhandledRejections = new Map();
process.on('unhandledRejection', (reason, promise) => {
  unhandledRejections.set(promise, reason);
});
process.on('rejectionHandled', (promise) => {
  unhandledRejections.delete(promise);
});const process = require('node:process');

const unhandledRejections = new Map();
process.on('unhandledRejection', (reason, promise) => {
  unhandledRejections.set(promise, reason);
});
process.on('rejectionHandled', (promise) => {
  unhandledRejections.delete(promise);
});

在这个例子中,unhandledRejections Map 将随着时间的推移而增长和缩小,反映了开始未处理然后变成处理的拒绝。可以定期在错误日志中记录此类错误(这可能最适合长时间运行的应用)或在进程退出时(这可能对脚本最方便)。

¥In this example, the unhandledRejections Map will grow and shrink over time, reflecting rejections that start unhandled and then become handled. It is possible to record such errors in an error log, either periodically (which is likely best for long-running application) or upon process exit (which is likely most convenient for scripts).

事件:'workerMessage'#

¥Event: 'workerMessage'

对于另一方使用 postMessageToThread() 发送的任何传入消息,都会触发 'workerMessage' 事件。

¥The 'workerMessage' event is emitted for any incoming message send by the other party by using postMessageToThread().

事件:'uncaughtException'#

¥Event: 'uncaughtException'

  • err <Error> 未捕获的异常。

    ¥err <Error> The uncaught exception.

  • origin <string> 指示异常是源自未处理的拒绝还是源自同步错误。可以是 'uncaughtException''unhandledRejection'。后者用于在基于 Promise 的异步上下文中发生异常(或者如果 Promise 被拒绝)并且 --unhandled-rejections 标志设置为 strictthrow(这是默认值)并且拒绝未被处理,或者当拒绝发生在命令行入口点的 ES 模块静态加载阶段。

    ¥origin <string> Indicates if the exception originates from an unhandled rejection or from a synchronous error. Can either be 'uncaughtException' or 'unhandledRejection'. The latter is used when an exception happens in a Promise based async context (or if a Promise is rejected) and --unhandled-rejections flag set to strict or throw (which is the default) and the rejection is not handled, or when a rejection happens during the command line entry point's ES module static loading phase.

当未捕获的 JavaScript 异常一直冒泡回到事件循环时,则会触发 'uncaughtException' 事件。默认情况下,Node.js 通过将堆栈跟踪打印到 stderr 并以代码 1 退出,覆盖任何先前设置的 process.exitCode 来处理此类异常。为 'uncaughtException' 事件添加句柄会覆盖此默认行为。或者,更改 'uncaughtException' 处理程序中的 process.exitCode,这将导致进程以提供的退出码退出。否则,在存在此类句柄的情况下,进程将以 0 退出。

¥The 'uncaughtException' event is emitted when an uncaught JavaScript exception bubbles all the way back to the event loop. By default, Node.js handles such exceptions by printing the stack trace to stderr and exiting with code 1, overriding any previously set process.exitCode. Adding a handler for the 'uncaughtException' event overrides this default behavior. Alternatively, change the process.exitCode in the 'uncaughtException' handler which will result in the process exiting with the provided exit code. Otherwise, in the presence of such handler the process will exit with 0.

import process from 'node:process';
import fs from 'node:fs';

process.on('uncaughtException', (err, origin) => {
  fs.writeSync(
    process.stderr.fd,
    `Caught exception: ${err}\n` +
    `Exception origin: ${origin}\n`,
  );
});

setTimeout(() => {
  console.log('This will still run.');
}, 500);

// Intentionally cause an exception, but don't catch it.
nonexistentFunc();
console.log('This will not run.');const process = require('node:process');
const fs = require('node:fs');

process.on('uncaughtException', (err, origin) => {
  fs.writeSync(
    process.stderr.fd,
    `Caught exception: ${err}\n` +
    `Exception origin: ${origin}\n`,
  );
});

setTimeout(() => {
  console.log('This will still run.');
}, 500);

// Intentionally cause an exception, but don't catch it.
nonexistentFunc();
console.log('This will not run.');

通过安装 'uncaughtExceptionMonitor' 监听器,可以在不覆盖退出进程的默认行为的情况下监视 'uncaughtException' 事件。

¥It is possible to monitor 'uncaughtException' events without overriding the default behavior to exit the process by installing a 'uncaughtExceptionMonitor' listener.

警告:正确使用 'uncaughtException'#

¥Warning: Using 'uncaughtException' correctly

'uncaughtException' 是用于异常处理的粗略机制,仅用作最后的手段。该事件不应用作 On Error Resume Next 的等同物。未处理的异常本质上意味着应用处于未定义状态。在没有从异常中正确恢复的情况下尝试恢复应用代码可能会导致其他不可预见和不可预测的问题。

¥'uncaughtException' is a crude mechanism for exception handling intended to be used only as a last resort. The event should not be used as an equivalent to On Error Resume Next. Unhandled exceptions inherently mean that an application is in an undefined state. Attempting to resume application code without properly recovering from the exception can cause additional unforeseen and unpredictable issues.

从事件句柄中抛出的异常将不会被捕获。而是,该进程将以非零退出码退出,并将打印堆栈跟踪。这是为了避免无限递归。

¥Exceptions thrown from within the event handler will not be caught. Instead the process will exit with a non-zero exit code and the stack trace will be printed. This is to avoid infinite recursion.

尝试在未捕获异常后正常恢复类似于升级计算机时拔掉电源线。十有八九,什么都没有发生。但是第十次,系统损坏了。

¥Attempting to resume normally after an uncaught exception can be similar to pulling out the power cord when upgrading a computer. Nine out of ten times, nothing happens. But the tenth time, the system becomes corrupted.

'uncaughtException' 的正确用法是在关闭进程之前对分配的资源(例如文件描述符、句柄等)执行同步清理。在 'uncaughtException' 之后恢复正常操作是不安全的。

¥The correct use of 'uncaughtException' is to perform synchronous cleanup of allocated resources (e.g. file descriptors, handles, etc) before shutting down the process. It is not safe to resume normal operation after 'uncaughtException'.

为了以更可靠的方式重新启动崩溃的应用,无论 'uncaughtException' 是否触发,都应该在单独的进程中使用外部监视器来检测应用故障并根据需要恢复或重新启动。

¥To restart a crashed application in a more reliable way, whether 'uncaughtException' is emitted or not, an external monitor should be employed in a separate process to detect application failures and recover or restart as needed.

事件:'uncaughtExceptionMonitor'#

¥Event: 'uncaughtExceptionMonitor'

  • err <Error> 未捕获的异常。

    ¥err <Error> The uncaught exception.

  • origin <string> 指示异常是源自未处理的拒绝还是源自同步错误。可以是 'uncaughtException''unhandledRejection'。后者用于在基于 Promise 的异步上下文中发生异常(或者如果 Promise 被拒绝)并且 --unhandled-rejections 标志设置为 strictthrow(这是默认值)并且拒绝未被处理,或者当拒绝发生在命令行入口点的 ES 模块静态加载阶段。

    ¥origin <string> Indicates if the exception originates from an unhandled rejection or from synchronous errors. Can either be 'uncaughtException' or 'unhandledRejection'. The latter is used when an exception happens in a Promise based async context (or if a Promise is rejected) and --unhandled-rejections flag set to strict or throw (which is the default) and the rejection is not handled, or when a rejection happens during the command line entry point's ES module static loading phase.

'uncaughtExceptionMonitor' 事件在 'uncaughtException' 事件触发或通过 process.setUncaughtExceptionCaptureCallback() 安装的钩子被调用之前触发。

¥The 'uncaughtExceptionMonitor' event is emitted before an 'uncaughtException' event is emitted or a hook installed via process.setUncaughtExceptionCaptureCallback() is called.

一旦触发 'uncaughtException' 事件,则安装 'uncaughtExceptionMonitor' 监听器不会更改行为。如果没有安装 'uncaughtException' 监听器,则进程仍然会崩溃。

¥Installing an 'uncaughtExceptionMonitor' listener does not change the behavior once an 'uncaughtException' event is emitted. The process will still crash if no 'uncaughtException' listener is installed.

import process from 'node:process';

process.on('uncaughtExceptionMonitor', (err, origin) => {
  MyMonitoringTool.logSync(err, origin);
});

// Intentionally cause an exception, but don't catch it.
nonexistentFunc();
// Still crashes Node.jsconst process = require('node:process');

process.on('uncaughtExceptionMonitor', (err, origin) => {
  MyMonitoringTool.logSync(err, origin);
});

// Intentionally cause an exception, but don't catch it.
nonexistentFunc();
// Still crashes Node.js

事件:'unhandledRejection'#

¥Event: 'unhandledRejection'

  • reason <Error> | <any> Promise 被拒绝的对象(通常是 Error 对象)。

    ¥reason <Error> | <any> The object with which the promise was rejected (typically an Error object).

  • promise <Promise> 被拒绝的 promise。

    ¥promise <Promise> The rejected promise.

每当 Promise 被拒绝并且在事件循环的一个轮询内没有错误句柄附加到 promise 时,则会触发 'unhandledRejection' 事件。使用 Promises 编程时,异常被封装为 "被拒绝的 promise"。拒绝可以使用 promise.catch() 捕获和处理,并通过 Promise 链传播。'unhandledRejection' 事件对于检测和跟踪尚未处理的被拒绝的 promise 很有用。

¥The 'unhandledRejection' event is emitted whenever a Promise is rejected and no error handler is attached to the promise within a turn of the event loop. When programming with Promises, exceptions are encapsulated as "rejected promises". Rejections can be caught and handled using promise.catch() and are propagated through a Promise chain. The 'unhandledRejection' event is useful for detecting and keeping track of promises that were rejected whose rejections have not yet been handled.

import process from 'node:process';

process.on('unhandledRejection', (reason, promise) => {
  console.log('Unhandled Rejection at:', promise, 'reason:', reason);
  // Application specific logging, throwing an error, or other logic here
});

somePromise.then((res) => {
  return reportToUser(JSON.pasre(res)); // Note the typo (`pasre`)
}); // No `.catch()` or `.then()`const process = require('node:process');

process.on('unhandledRejection', (reason, promise) => {
  console.log('Unhandled Rejection at:', promise, 'reason:', reason);
  // Application specific logging, throwing an error, or other logic here
});

somePromise.then((res) => {
  return reportToUser(JSON.pasre(res)); // Note the typo (`pasre`)
}); // No `.catch()` or `.then()`

以下也将触发 'unhandledRejection' 事件被触发:

¥The following will also trigger the 'unhandledRejection' event to be emitted:

import process from 'node:process';

function SomeResource() {
  // Initially set the loaded status to a rejected promise
  this.loaded = Promise.reject(new Error('Resource not yet loaded!'));
}

const resource = new SomeResource();
// no .catch or .then on resource.loaded for at least a turnconst process = require('node:process');

function SomeResource() {
  // Initially set the loaded status to a rejected promise
  this.loaded = Promise.reject(new Error('Resource not yet loaded!'));
}

const resource = new SomeResource();
// no .catch or .then on resource.loaded for at least a turn

在此示例情况下,可以将拒绝作为开发者错误进行跟踪,这通常是其他 'unhandledRejection' 事件的情况。为了解决此类故障,可以将非操作 .catch(() => { }) 句柄附加到 resource.loaded,这将阻止触发 'unhandledRejection' 事件。

¥In this example case, it is possible to track the rejection as a developer error as would typically be the case for other 'unhandledRejection' events. To address such failures, a non-operational .catch(() => { }) handler may be attached to resource.loaded, which would prevent the 'unhandledRejection' event from being emitted.

事件:'warning'#

¥Event: 'warning'

  • warning <Error> 警告的主要属性是:

    ¥warning <Error> Key properties of the warning are:

    • name <string> 警告的名称。默认值:'Warning'

      ¥name <string> The name of the warning. Default: 'Warning'.

    • message <string> 系统提供的警告描述。

      ¥message <string> A system-provided description of the warning.

    • stack <string> 代码中触发警告的位置的堆栈跟踪。

      ¥stack <string> A stack trace to the location in the code where the warning was issued.

每当 Node.js 触发进程警告时,则会触发 'warning' 事件。

¥The 'warning' event is emitted whenever Node.js emits a process warning.

进程警告类似于错误,因为其描述了引起用户注意的异常情况。但是,警告不是正常 Node.js 和 JavaScript 错误处理流程的一部分。Node.js 可以在检测到可能导致次优应用性能、错误或安全漏洞的不良编码实践时触发警告。

¥A process warning is similar to an error in that it describes exceptional conditions that are being brought to the user's attention. However, warnings are not part of the normal Node.js and JavaScript error handling flow. Node.js can emit warnings whenever it detects bad coding practices that could lead to sub-optimal application performance, bugs, or security vulnerabilities.

import process from 'node:process';

process.on('warning', (warning) => {
  console.warn(warning.name);    // Print the warning name
  console.warn(warning.message); // Print the warning message
  console.warn(warning.stack);   // Print the stack trace
});const process = require('node:process');

process.on('warning', (warning) => {
  console.warn(warning.name);    // Print the warning name
  console.warn(warning.message); // Print the warning message
  console.warn(warning.stack);   // Print the stack trace
});

默认情况下,Node.js 会将进程警告打印到 stderr--no-warnings 命令行选项可用于抑制默认控制台输出,但 'warning' 事件仍将由 process 对象触发。目前,无法抑制除弃用警告之外的特定警告类型。要抑制弃用警告,请检查 --no-deprecation 标志。

¥By default, Node.js will print process warnings to stderr. The --no-warnings command-line option can be used to suppress the default console output but the 'warning' event will still be emitted by the process object. Currently, it is not possible to suppress specific warning types other than deprecation warnings. To suppress deprecation warnings, check out the --no-deprecation flag.

以下示例说明了在向事件添加过多监听器时打印到 stderr 的警告:

¥The following example illustrates the warning that is printed to stderr when too many listeners have been added to an event:

$ node
> events.defaultMaxListeners = 1;
> process.on('foo', () => {});
> process.on('foo', () => {});
> (node:38638) MaxListenersExceededWarning: Possible EventEmitter memory leak
detected. 2 foo listeners added. Use emitter.setMaxListeners() to increase limit 

相比之下,以下示例关闭默认警告输出并向 'warning' 事件添加自定义句柄:

¥In contrast, the following example turns off the default warning output and adds a custom handler to the 'warning' event:

$ node --no-warnings
> const p = process.on('warning', (warning) => console.warn('Do not do that!'));
> events.defaultMaxListeners = 1;
> process.on('foo', () => {});
> process.on('foo', () => {});
> Do not do that! 

--trace-warnings 命令行选项可用于使警告的默认控制台输出包括警告的完整堆栈跟踪。

¥The --trace-warnings command-line option can be used to have the default console output for warnings include the full stack trace of the warning.

使用 --throw-deprecation 命令行标志启动 Node.js 将导致自定义弃用警告作为异常抛出。

¥Launching Node.js using the --throw-deprecation command-line flag will cause custom deprecation warnings to be thrown as exceptions.

使用 --trace-deprecation 命令行标志将导致自定义弃用与堆栈跟踪一起打印到 stderr

¥Using the --trace-deprecation command-line flag will cause the custom deprecation to be printed to stderr along with the stack trace.

使用 --no-deprecation 命令行标志将抑制自定义弃用的所有报告。

¥Using the --no-deprecation command-line flag will suppress all reporting of the custom deprecation.

*-deprecation 命令行标志仅影响使用名称 'DeprecationWarning' 的警告。

¥The *-deprecation command-line flags only affect warnings that use the name 'DeprecationWarning'.

触发自定义警告#

¥Emitting custom warnings

请参阅 process.emitWarning() 方法以触发自定义或特定于应用的警告。

¥See the process.emitWarning() method for issuing custom or application-specific warnings.

Node.js 警告名称#

¥Node.js warning names

Node.js 触发的警告类型(由 name 属性标识)没有严格的指导方针。可以随时添加新类型的警告。一些最常见的警告类型包括:

¥There are no strict guidelines for warning types (as identified by the name property) emitted by Node.js. New types of warnings can be added at any time. A few of the warning types that are most common include:

  • 'DeprecationWarning' - 指示使用已弃用的 Node.js API 或功能。此类警告必须包含标识 弃用码'code' 属性。

    ¥'DeprecationWarning' - Indicates use of a deprecated Node.js API or feature. Such warnings must include a 'code' property identifying the deprecation code.

  • 'ExperimentalWarning' - 指示使用实验性 Node.js API 或功能。必须谨慎使用此类功能,因为它们可能随时更改,并且不受与受支持功能相同的严格语义版本控制和长期支持政策的约束。

    ¥'ExperimentalWarning' - Indicates use of an experimental Node.js API or feature. Such features must be used with caution as they may change at any time and are not subject to the same strict semantic-versioning and long-term support policies as supported features.

  • 'MaxListenersExceededWarning' - 表示在 EventEmitterEventTarget 上注册了太多给定事件的监听器。这通常表示内存泄漏。

    ¥'MaxListenersExceededWarning' - Indicates that too many listeners for a given event have been registered on either an EventEmitter or EventTarget. This is often an indication of a memory leak.

  • 'TimeoutOverflowWarning' - 指示已向 setTimeout()setInterval() 函数提供了无法容纳在 32 位带符号整数中的数值。

    ¥'TimeoutOverflowWarning' - Indicates that a numeric value that cannot fit within a 32-bit signed integer has been provided to either the setTimeout() or setInterval() functions.

  • 'UnsupportedWarning' - 指示使用不受支持的选项或功能,这些选项或功能将被忽略而不是被视为错误。一个示例是在使用 HTTP/2 兼容性 API 时使用 HTTP 响应状态消息。

    ¥'UnsupportedWarning' - Indicates use of an unsupported option or feature that will be ignored rather than treated as an error. One example is use of the HTTP response status message when using the HTTP/2 compatibility API.

事件:'worker'#

¥Event: 'worker'

创建新的 <Worker> 线程后会触发 'worker' 事件。

¥The 'worker' event is emitted after a new <Worker> thread has been created.

信号事件#

¥Signal events

当 Node.js 进程收到信号时,则将触发信号事件。请参阅 signal(7) 以获取标准 POSIX 信号名称的列表,例如 'SIGINT''SIGHUP' 等。

¥Signal events will be emitted when the Node.js process receives a signal. Please refer to signal(7) for a listing of standard POSIX signal names such as 'SIGINT', 'SIGHUP', etc.

信号在 Worker 线程上不可用。

¥Signals are not available on Worker threads.

信号句柄将接收信号的名称('SIGINT''SIGTERM' 等)作为第一个参数。

¥The signal handler will receive the signal's name ('SIGINT', 'SIGTERM', etc.) as the first argument.

每个事件的名称将是信号的大写通用名称(例如 'SIGINT' 表示 SIGINT 信号)。

¥The name of each event will be the uppercase common name for the signal (e.g. 'SIGINT' for SIGINT signals).

import process from 'node:process';

// Begin reading from stdin so the process does not exit.
process.stdin.resume();

process.on('SIGINT', () => {
  console.log('Received SIGINT. Press Control-D to exit.');
});

// Using a single function to handle multiple signals
function handle(signal) {
  console.log(`Received ${signal}`);
}

process.on('SIGINT', handle);
process.on('SIGTERM', handle);const process = require('node:process');

// Begin reading from stdin so the process does not exit.
process.stdin.resume();

process.on('SIGINT', () => {
  console.log('Received SIGINT. Press Control-D to exit.');
});

// Using a single function to handle multiple signals
function handle(signal) {
  console.log(`Received ${signal}`);
}

process.on('SIGINT', handle);
process.on('SIGTERM', handle);
  • 'SIGUSR1' 由 Node.js 保留以启动 debugger。可以安装监听器,但这样做可能会干扰调试器。

    ¥'SIGUSR1' is reserved by Node.js to start the debugger. It's possible to install a listener but doing so might interfere with the debugger.

  • 'SIGTERM''SIGINT' 在非 Windows 平台上具有默认的句柄,其在使用代码 128 + signal number 退出之前重置终端模式。如果这些信号之一安装了监听器,则其默认行为将被删除(Node.js 将不再退出)。

    ¥'SIGTERM' and 'SIGINT' have default handlers on non-Windows platforms that reset the terminal mode before exiting with code 128 + signal number. If one of these signals has a listener installed, its default behavior will be removed (Node.js will no longer exit).

  • 'SIGPIPE' 默认情况下忽略。它可以安装监听器。

    ¥'SIGPIPE' is ignored by default. It can have a listener installed.

  • 'SIGHUP' 在 Windows 上是在关闭控制台窗口时生成,在其他平台上是在各种类似条件下生成。参见信号(7)。它可以安装监听器,但是 Node.js 将在大约 10 秒后被 Windows 无条件地终止。在非 Windows 平台上,SIGHUP 的默认行为是终止 Node.js,但一旦安装了监听器,则其默认行为将被删除。

    ¥'SIGHUP' is generated on Windows when the console window is closed, and on other platforms under various similar conditions. See signal(7). It can have a listener installed, however Node.js will be unconditionally terminated by Windows about 10 seconds later. On non-Windows platforms, the default behavior of SIGHUP is to terminate Node.js, but once a listener has been installed its default behavior will be removed.

  • 'SIGTERM' Windows 上不支持,可以监听。

    ¥'SIGTERM' is not supported on Windows, it can be listened on.

  • 所有平台都支持来自终端的 'SIGINT',并且通常可以使用 Ctrl+C 生成(尽管这可能是可配置的)。当 终端原始模式 使能并且使用 Ctrl+C 时不会生成。

    ¥'SIGINT' from the terminal is supported on all platforms, and can usually be generated with Ctrl+C (though this may be configurable). It is not generated when terminal raw mode is enabled and Ctrl+C is used.

  • 在 Windows 上按下 Ctrl+Break 时会传递 'SIGBREAK'。在非 Windows 平台上,它可以被监听,但无法发送或生成它。

    ¥'SIGBREAK' is delivered on Windows when Ctrl+Break is pressed. On non-Windows platforms, it can be listened on, but there is no way to send or generate it.

  • 'SIGWINCH' 当调整控制台大小时会发送。在 Windows 上,这只会发生在当光标移动时写入控制台,或者当在原始模式下使用可读的终端时。

    ¥'SIGWINCH' is delivered when the console has been resized. On Windows, this will only happen on write to the console when the cursor is being moved, or when a readable tty is used in raw mode.

  • 'SIGKILL' 不能安装监听器,它会无条件地终止所有平台上的 Node.js。

    ¥'SIGKILL' cannot have a listener installed, it will unconditionally terminate Node.js on all platforms.

  • 'SIGSTOP' 不能安装监听器。

    ¥'SIGSTOP' cannot have a listener installed.

  • 'SIGBUS''SIGFPE''SIGSEGV''SIGILL',当不使用 kill(2) 人为引发时,本质上会使进程处于调用 JS 监听器不安全的状态。这样做可能会导致进程停止响应。

    ¥'SIGBUS', 'SIGFPE', 'SIGSEGV', and 'SIGILL', when not raised artificially using kill(2), inherently leave the process in a state from which it is not safe to call JS listeners. Doing so might cause the process to stop responding.

  • 0 可以发送来测试进程是否存在,如果进程存在则没影响,如果进程不存在则抛出错误。

    ¥0 can be sent to test for the existence of a process, it has no effect if the process exists, but will throw an error if the process does not exist.

Windows 不支持信号,因此没有等价的使用信号来终止,但 Node.js 提供了一些对 process.kill()subprocess.kill() 的模拟:

¥Windows does not support signals so has no equivalent to termination by signal, but Node.js offers some emulation with process.kill(), and subprocess.kill():

  • 发送 SIGINTSIGTERM、和 SIGKILL 会导致目标进程无条件的终止,之后子进程会报告进程被信号终止。

    ¥Sending SIGINT, SIGTERM, and SIGKILL will cause the unconditional termination of the target process, and afterwards, subprocess will report that the process was terminated by signal.

  • 发送信号 0 可以作为独立于平台的方式来测试进程是否存在。

    ¥Sending signal 0 can be used as a platform independent way to test for the existence of a process.

process.abort()#

process.abort() 方法会导致 Node.js 进程立即退出并生成一个核心文件。

¥The process.abort() method causes the Node.js process to exit immediately and generate a core file.

此特性在 Worker 线程中不可用。

¥This feature is not available in Worker threads.

process.allowedNodeEnvironmentFlags#

process.allowedNodeEnvironmentFlags 属性是 NODE_OPTIONS 环境变量中允许的特殊的只读 Set 标志。

¥The process.allowedNodeEnvironmentFlags property is a special, read-only Set of flags allowable within the NODE_OPTIONS environment variable.

process.allowedNodeEnvironmentFlags 继承了 Set,但覆盖了 Set.prototype.has 以识别几种不同的可能标志表示。在以下情况下,process.allowedNodeEnvironmentFlags.has() 将返回 true

¥process.allowedNodeEnvironmentFlags extends Set, but overrides Set.prototype.has to recognize several different possible flag representations. process.allowedNodeEnvironmentFlags.has() will return true in the following cases:

  • 标志可以省略前导单 (-) 或双 (--) 破折号;例如,inspect-brk 代表 --inspect-brkr 代表 -r

    ¥Flags may omit leading single (-) or double (--) dashes; e.g., inspect-brk for --inspect-brk, or r for -r.

  • 传递给 V8 的标志(如 --v8-options 中所列)可以将一个或多个非前导破折号替换为下划线,反之亦然;例如,--perf_basic_prof--perf-basic-prof--perf_basic-prof 等。

    ¥Flags passed through to V8 (as listed in --v8-options) may replace one or more non-leading dashes for an underscore, or vice-versa; e.g., --perf_basic_prof, --perf-basic-prof, --perf_basic-prof, etc.

  • 标志可能包含一个或多个等号 (=) 字符;包括第一个等号在内的所有字符都将被忽略;例如,--stack-trace-limit=100

    ¥Flags may contain one or more equals (=) characters; all characters after and including the first equals will be ignored; e.g., --stack-trace-limit=100.

  • NODE_OPTIONS 中必须允许标志。

    ¥Flags must be allowable within NODE_OPTIONS.

遍历 process.allowedNodeEnvironmentFlags 时,flags 只会出现一次;每个都以一个或多个破折号开头。传给 V8 的标志将包含下划线而不是非前导破折号:

¥When iterating over process.allowedNodeEnvironmentFlags, flags will appear only once; each will begin with one or more dashes. Flags passed through to V8 will contain underscores instead of non-leading dashes:

import { allowedNodeEnvironmentFlags } from 'node:process';

allowedNodeEnvironmentFlags.forEach((flag) => {
  // -r
  // --inspect-brk
  // --abort_on_uncaught_exception
  // ...
});const { allowedNodeEnvironmentFlags } = require('node:process');

allowedNodeEnvironmentFlags.forEach((flag) => {
  // -r
  // --inspect-brk
  // --abort_on_uncaught_exception
  // ...
});

process.allowedNodeEnvironmentFlags 的方法 add()clear()delete() 什么都不做,会静默失败。

¥The methods add(), clear(), and delete() of process.allowedNodeEnvironmentFlags do nothing, and will fail silently.

如果 Node.js 是在没有 NODE_OPTIONS 支持的情况下编译的(如 process.config 所示),process.allowedNodeEnvironmentFlags 将包含允许的内容。

¥If Node.js was compiled without NODE_OPTIONS support (shown in process.config), process.allowedNodeEnvironmentFlags will contain what would have been allowable.

process.arch#

为其编译 Node.js 二进制文件的操作系统 CPU 架构。可能的值是:'arm''arm64''ia32''loong64''mips''mipsel''ppc''ppc64''riscv64''s390''s390x''x64'

¥The operating system CPU architecture for which the Node.js binary was compiled. Possible values are: 'arm', 'arm64', 'ia32', 'loong64', 'mips', 'mipsel', 'ppc', 'ppc64', 'riscv64', 's390', 's390x', and 'x64'.

import { arch } from 'node:process';

console.log(`This processor architecture is ${arch}`);const { arch } = require('node:process');

console.log(`This processor architecture is ${arch}`);

process.argv#

process.argv 属性返回数组,其中包含启动 Node.js 进程时传入的命令行参数。第一个元素将是 process.execPath。如果需要访问 argv[0] 的原始值,请参阅 process.argv0。第二个元素将是正在执行的 JavaScript 文件的路径。其余元素将是任何其他命令行参数。

¥The process.argv property returns an array containing the command-line arguments passed when the Node.js process was launched. The first element will be process.execPath. See process.argv0 if access to the original value of argv[0] is needed. The second element will be the path to the JavaScript file being executed. The remaining elements will be any additional command-line arguments.

例如,假设 process-args.js 有以下脚本:

¥For example, assuming the following script for process-args.js:

import { argv } from 'node:process';

// print process.argv
argv.forEach((val, index) => {
  console.log(`${index}: ${val}`);
});const { argv } = require('node:process');

// print process.argv
argv.forEach((val, index) => {
  console.log(`${index}: ${val}`);
});

以如下方式启动 Node.js 进程:

¥Launching the Node.js process as:

node process-args.js one two=three four 

将生成输出:

¥Would generate the output:

0: /usr/local/bin/node
1: /Users/mjr/work/node/process-args.js
2: one
3: two=three
4: four 

process.argv0#

process.argv0 属性存储了 Node.js 启动时传入的 argv[0] 原始值的只读副本。

¥The process.argv0 property stores a read-only copy of the original value of argv[0] passed when Node.js starts.

$ bash -c 'exec -a customArgv0 ./node'
> process.argv[0]
'/Volumes/code/external/node/out/Release/node'
> process.argv0
'customArgv0' 

process.channel#

如果 Node.js 进程是使用 IPC 通道生成的(请参阅 子进程 文档),则 process.channel 属性是对 IPC 通道的引用。如果不存在 IPC 通道,则此属性为 undefined

¥If the Node.js process was spawned with an IPC channel (see the Child Process documentation), the process.channel property is a reference to the IPC channel. If no IPC channel exists, this property is undefined.

process.channel.ref()#

如果之前已调用过 .unref(),则此方法使 IPC 通道保持进程的事件循环运行。

¥This method makes the IPC channel keep the event loop of the process running if .unref() has been called before.

通常,这是通过 process 对象上的 'disconnect''message' 监听器的数量来管理的。但是,此方法可用于显式请求特定行为。

¥Typically, this is managed through the number of 'disconnect' and 'message' listeners on the process object. However, this method can be used to explicitly request a specific behavior.

process.channel.unref()#

此方法使 IPC 通道不会保持进程的事件循环运行,并且即使在通道打开时也让它完成。

¥This method makes the IPC channel not keep the event loop of the process running, and lets it finish even while the channel is open.

通常,这是通过 process 对象上的 'disconnect''message' 监听器的数量来管理的。但是,此方法可用于显式请求特定行为。

¥Typically, this is managed through the number of 'disconnect' and 'message' listeners on the process object. However, this method can be used to explicitly request a specific behavior.

process.chdir(directory)#

process.chdir() 方法更改 Node.js 进程的当前工作目录,如果失败则抛出异常(例如,如果指定的 directory 不存在)。

¥The process.chdir() method changes the current working directory of the Node.js process or throws an exception if doing so fails (for instance, if the specified directory does not exist).

import { chdir, cwd } from 'node:process';

console.log(`Starting directory: ${cwd()}`);
try {
  chdir('/tmp');
  console.log(`New directory: ${cwd()}`);
} catch (err) {
  console.error(`chdir: ${err}`);
}const { chdir, cwd } = require('node:process');

console.log(`Starting directory: ${cwd()}`);
try {
  chdir('/tmp');
  console.log(`New directory: ${cwd()}`);
} catch (err) {
  console.error(`chdir: ${err}`);
}

此特性在 Worker 线程中不可用。

¥This feature is not available in Worker threads.

process.config#

process.config 属性返回一个冻结的 Object,其中包含用于编译当前 Node.js 可执行文件的配置选项的 JavaScript 表示。这与运行 ./configure 脚本时生成的 config.gypi 文件相同。

¥The process.config property returns a frozen Object containing the JavaScript representation of the configure options used to compile the current Node.js executable. This is the same as the config.gypi file that was produced when running the ./configure script.

可能的输出示例如下所示:

¥An example of the possible output looks like:

{
  target_defaults:
   { cflags: [],
     default_configuration: 'Release',
     defines: [],
     include_dirs: [],
     libraries: [] },
  variables:
   {
     host_arch: 'x64',
     napi_build_version: 5,
     node_install_npm: 'true',
     node_prefix: '',
     node_shared_cares: 'false',
     node_shared_http_parser: 'false',
     node_shared_libuv: 'false',
     node_shared_zlib: 'false',
     node_use_openssl: 'true',
     node_shared_openssl: 'false',
     target_arch: 'x64',
     v8_use_snapshot: 1
   }
} 

process.connected#

如果 Node.js 进程是使用 IPC 通道生成的(请参阅 子进程集群 文档),只要连接了 IPC 通道,process.connected 属性就会返回 true,并在调用 process.disconnect() 后返回 false

¥If the Node.js process is spawned with an IPC channel (see the Child Process and Cluster documentation), the process.connected property will return true so long as the IPC channel is connected and will return false after process.disconnect() is called.

一旦 process.connectedfalse,就不能再使用 process.send() 通过 IPC 通道发送消息。

¥Once process.connected is false, it is no longer possible to send messages over the IPC channel using process.send().

process.constrainedMemory()#

稳定性: 1 - 实验性的

¥Stability: 1 - Experimental

根据操作系统施加的限制获取进程可用的内存量(以字节为单位)。如果没有这样的约束,或者约束未知,则返回 0

¥Gets the amount of memory available to the process (in bytes) based on limits imposed by the OS. If there is no such constraint, or the constraint is unknown, 0 is returned.

有关详细信息,请参阅 uv_get_constrained_memory

¥See uv_get_constrained_memory for more information.

process.availableMemory()#

稳定性: 1 - 实验性的

¥Stability: 1 - Experimental

获取进程仍可用的空闲内存量(以字节为单位)。

¥Gets the amount of free memory that is still available to the process (in bytes).

有关详细信息,请参阅 uv_get_available_memory

¥See uv_get_available_memory for more information.

process.cpuUsage([previousValue])#

process.cpuUsage() 方法在具有属性 usersystem 的对象中返回当前进程的用户和系统 CPU 时间使用情况,其值为微秒值(百万分之一秒)。这些值分别测量在用户和系统代码中花费的时间,如果多个 CPU 内核为此进程执行工作,则最终可能会大于实际经过的时间。

¥The process.cpuUsage() method returns the user and system CPU time usage of the current process, in an object with properties user and system, whose values are microsecond values (millionth of a second). These values measure time spent in user and system code respectively, and may end up being greater than actual elapsed time if multiple CPU cores are performing work for this process.

先前调用 process.cpuUsage() 的结果可以作为参数传给函数,以获取差异读数。

¥The result of a previous call to process.cpuUsage() can be passed as the argument to the function, to get a diff reading.

import { cpuUsage } from 'node:process';

const startUsage = cpuUsage();
// { user: 38579, system: 6986 }

// spin the CPU for 500 milliseconds
const now = Date.now();
while (Date.now() - now < 500);

console.log(cpuUsage(startUsage));
// { user: 514883, system: 11226 }const { cpuUsage } = require('node:process');

const startUsage = cpuUsage();
// { user: 38579, system: 6986 }

// spin the CPU for 500 milliseconds
const now = Date.now();
while (Date.now() - now < 500);

console.log(cpuUsage(startUsage));
// { user: 514883, system: 11226 }

process.cwd()#

process.cwd() 方法返回 Node.js 进程的当前工作目录。

¥The process.cwd() method returns the current working directory of the Node.js process.

import { cwd } from 'node:process';

console.log(`Current directory: ${cwd()}`);const { cwd } = require('node:process');

console.log(`Current directory: ${cwd()}`);

process.debugPort#

启用时 Node.js 调试器使用的端口。

¥The port used by the Node.js debugger when enabled.

import process from 'node:process';

process.debugPort = 5858;const process = require('node:process');

process.debugPort = 5858;

process.disconnect()#

如果 Node.js 进程是使用 IPC 通道生成的(请参阅 子进程集群 文档),process.disconnect() 方法将关闭到父进程的 IPC 通道,允许子进程在没有其他连接保持活动时正常退出 .

¥If the Node.js process is spawned with an IPC channel (see the Child Process and Cluster documentation), the process.disconnect() method will close the IPC channel to the parent process, allowing the child process to exit gracefully once there are no other connections keeping it alive.

调用 process.disconnect() 的效果和从父进程调用 ChildProcess.disconnect() 是一样的。

¥The effect of calling process.disconnect() is the same as calling ChildProcess.disconnect() from the parent process.

如果 Node.js 进程不是使用 IPC 通道衍生,则 process.disconnect() 将是 undefined

¥If the Node.js process was not spawned with an IPC channel, process.disconnect() will be undefined.

process.dlopen(module, filename[, flags])#

process.dlopen() 方法允许动态加载共享对象。require() 主要用于加载 C++ 插件,除非特殊情况,否则不应直接使用。换句话说,require() 应该优先于 process.dlopen(),除非有特定的原因,例如自定义 dlopen 标志或从 ES 模块加载。

¥The process.dlopen() method allows dynamically loading shared objects. It is primarily used by require() to load C++ Addons, and should not be used directly, except in special cases. In other words, require() should be preferred over process.dlopen() unless there are specific reasons such as custom dlopen flags or loading from ES modules.

flags 参数是整数,允许指定 dlopen 行为。有关详细信息,请参阅 os.constants.dlopen 文档。

¥The flags argument is an integer that allows to specify dlopen behavior. See the os.constants.dlopen documentation for details.

调用 process.dlopen() 时的一个重要要求是必须传入 module 实例。然后可以通过 module.exports 访问由 C++ 插件导出的函数。

¥An important requirement when calling process.dlopen() is that the module instance must be passed. Functions exported by the C++ Addon are then accessible via module.exports.

下面的示例显示了如何加载名为 local.node 的 C++ 插件,该插件导出 foo 函数。通过传入 RTLD_NOW 常量,在调用返回之前加载所有符号。在此示例中,假定常量可用。

¥The example below shows how to load a C++ Addon, named local.node, that exports a foo function. All the symbols are loaded before the call returns, by passing the RTLD_NOW constant. In this example the constant is assumed to be available.

import { dlopen } from 'node:process';
import { constants } from 'node:os';
import { fileURLToPath } from 'node:url';

const module = { exports: {} };
dlopen(module, fileURLToPath(new URL('local.node', import.meta.url)),
       constants.dlopen.RTLD_NOW);
module.exports.foo();const { dlopen } = require('node:process');
const { constants } = require('node:os');
const { join } = require('node:path');

const module = { exports: {} };
dlopen(module, join(__dirname, 'local.node'), constants.dlopen.RTLD_NOW);
module.exports.foo();

process.emitWarning(warning[, options])#

  • warning <string> | <Error> 要触发的警告。

    ¥warning <string> | <Error> The warning to emit.

  • options <Object>

    • type <string>warningString 时,type 是用于触发的警告类型的名称。默认值:'Warning'

      ¥type <string> When warning is a String, type is the name to use for the type of warning being emitted. Default: 'Warning'.

    • code <string> 触发的警告实例的唯一标识符。

      ¥code <string> A unique identifier for the warning instance being emitted.

    • ctor <Function>warningString 时,ctor 是可选函数,用于限制生成的堆栈跟踪。默认值:process.emitWarning

      ¥ctor <Function> When warning is a String, ctor is an optional function used to limit the generated stack trace. Default: process.emitWarning.

    • detail <string> 要包含在错误中的额外文本。

      ¥detail <string> Additional text to include with the error.

process.emitWarning() 方法可用于触发自定义或特定于应用的进程警告。这些可以通过向 'warning' 事件添加句柄来监听。

¥The process.emitWarning() method can be used to emit custom or application specific process warnings. These can be listened for by adding a handler to the 'warning' event.

import { emitWarning } from 'node:process';

// Emit a warning with a code and additional detail.
emitWarning('Something happened!', {
  code: 'MY_WARNING',
  detail: 'This is some additional information',
});
// Emits:
// (node:56338) [MY_WARNING] Warning: Something happened!
// This is some additional informationconst { emitWarning } = require('node:process');

// Emit a warning with a code and additional detail.
emitWarning('Something happened!', {
  code: 'MY_WARNING',
  detail: 'This is some additional information',
});
// Emits:
// (node:56338) [MY_WARNING] Warning: Something happened!
// This is some additional information

在此示例中,Error 对象由 process.emitWarning() 在内部生成并传给 'warning' 句柄。

¥In this example, an Error object is generated internally by process.emitWarning() and passed through to the 'warning' handler.

import process from 'node:process';

process.on('warning', (warning) => {
  console.warn(warning.name);    // 'Warning'
  console.warn(warning.message); // 'Something happened!'
  console.warn(warning.code);    // 'MY_WARNING'
  console.warn(warning.stack);   // Stack trace
  console.warn(warning.detail);  // 'This is some additional information'
});const process = require('node:process');

process.on('warning', (warning) => {
  console.warn(warning.name);    // 'Warning'
  console.warn(warning.message); // 'Something happened!'
  console.warn(warning.code);    // 'MY_WARNING'
  console.warn(warning.stack);   // Stack trace
  console.warn(warning.detail);  // 'This is some additional information'
});

如果 warning 作为 Error 对象传入,则忽略 options 参数。

¥If warning is passed as an Error object, the options argument is ignored.

process.emitWarning(warning[, type[, code]][, ctor])#

  • warning <string> | <Error> 要触发的警告。

    ¥warning <string> | <Error> The warning to emit.

  • type <string>warningString 时,type 是用于触发的警告类型的名称。默认值:'Warning'

    ¥type <string> When warning is a String, type is the name to use for the type of warning being emitted. Default: 'Warning'.

  • code <string> 触发的警告实例的唯一标识符。

    ¥code <string> A unique identifier for the warning instance being emitted.

  • ctor <Function>warningString 时,ctor 是可选函数,用于限制生成的堆栈跟踪。默认值:process.emitWarning

    ¥ctor <Function> When warning is a String, ctor is an optional function used to limit the generated stack trace. Default: process.emitWarning.

process.emitWarning() 方法可用于触发自定义或特定于应用的进程警告。这些可以通过向 'warning' 事件添加句柄来监听。

¥The process.emitWarning() method can be used to emit custom or application specific process warnings. These can be listened for by adding a handler to the 'warning' event.

import { emitWarning } from 'node:process';

// Emit a warning using a string.
emitWarning('Something happened!');
// Emits: (node: 56338) Warning: Something happened!const { emitWarning } = require('node:process');

// Emit a warning using a string.
emitWarning('Something happened!');
// Emits: (node: 56338) Warning: Something happened!
import { emitWarning } from 'node:process';

// Emit a warning using a string and a type.
emitWarning('Something Happened!', 'CustomWarning');
// Emits: (node:56338) CustomWarning: Something Happened!const { emitWarning } = require('node:process');

// Emit a warning using a string and a type.
emitWarning('Something Happened!', 'CustomWarning');
// Emits: (node:56338) CustomWarning: Something Happened!
import { emitWarning } from 'node:process';

emitWarning('Something happened!', 'CustomWarning', 'WARN001');
// Emits: (node:56338) [WARN001] CustomWarning: Something happened!const { emitWarning } = require('node:process');

process.emitWarning('Something happened!', 'CustomWarning', 'WARN001');
// Emits: (node:56338) [WARN001] CustomWarning: Something happened!

在前面的每个示例中,Error 对象由 process.emitWarning() 在内部生成并传给 'warning' 句柄。

¥In each of the previous examples, an Error object is generated internally by process.emitWarning() and passed through to the 'warning' handler.

import process from 'node:process';

process.on('warning', (warning) => {
  console.warn(warning.name);
  console.warn(warning.message);
  console.warn(warning.code);
  console.warn(warning.stack);
});const process = require('node:process');

process.on('warning', (warning) => {
  console.warn(warning.name);
  console.warn(warning.message);
  console.warn(warning.code);
  console.warn(warning.stack);
});

如果 warning 作为 Error 对象传入,则它将被不加修改地传给 'warning' 事件句柄(并且可选的 typecodector 参数将被忽略):

¥If warning is passed as an Error object, it will be passed through to the 'warning' event handler unmodified (and the optional type, code and ctor arguments will be ignored):

import { emitWarning } from 'node:process';

// Emit a warning using an Error object.
const myWarning = new Error('Something happened!');
// Use the Error name property to specify the type name
myWarning.name = 'CustomWarning';
myWarning.code = 'WARN001';

emitWarning(myWarning);
// Emits: (node:56338) [WARN001] CustomWarning: Something happened!const { emitWarning } = require('node:process');

// Emit a warning using an Error object.
const myWarning = new Error('Something happened!');
// Use the Error name property to specify the type name
myWarning.name = 'CustomWarning';
myWarning.code = 'WARN001';

emitWarning(myWarning);
// Emits: (node:56338) [WARN001] CustomWarning: Something happened!

如果 warning 不是字符串或 Error 对象,则抛出 TypeError

¥A TypeError is thrown if warning is anything other than a string or Error object.

虽然进程警告使用 Error 对象,但进程警告机制并不能替代正常的错误处理机制。

¥While process warnings use Error objects, the process warning mechanism is not a replacement for normal error handling mechanisms.

如果警告 type'DeprecationWarning',则执行以下额外处理:

¥The following additional handling is implemented if the warning type is 'DeprecationWarning':

  • 如果使用 --throw-deprecation 命令行标志,则弃用警告将作为异常抛出,而不是作为事件触发。

    ¥If the --throw-deprecation command-line flag is used, the deprecation warning is thrown as an exception rather than being emitted as an event.

  • 如果使用 --no-deprecation 命令行标志,则会取消弃用警告。

    ¥If the --no-deprecation command-line flag is used, the deprecation warning is suppressed.

  • 如果使用 --trace-deprecation 命令行标志,则弃用警告将与完整堆栈跟踪一起打印到 stderr

    ¥If the --trace-deprecation command-line flag is used, the deprecation warning is printed to stderr along with the full stack trace.

避免重复警告#

¥Avoiding duplicate warnings

作为最佳实践,每个进程只应触发一次警告。为此,则将 emitWarning() 放在布尔值后面。

¥As a best practice, warnings should be emitted only once per process. To do so, place the emitWarning() behind a boolean.

import { emitWarning } from 'node:process';

function emitMyWarning() {
  if (!emitMyWarning.warned) {
    emitMyWarning.warned = true;
    emitWarning('Only warn once!');
  }
}
emitMyWarning();
// Emits: (node: 56339) Warning: Only warn once!
emitMyWarning();
// Emits nothingconst { emitWarning } = require('node:process');

function emitMyWarning() {
  if (!emitMyWarning.warned) {
    emitMyWarning.warned = true;
    emitWarning('Only warn once!');
  }
}
emitMyWarning();
// Emits: (node: 56339) Warning: Only warn once!
emitMyWarning();
// Emits nothing

process.env#

process.env 属性返回包含用户环境的对象。参见环境(7)。

¥The process.env property returns an object containing the user environment. See environ(7).

此对象的示例如下所示:

¥An example of this object looks like:

{
  TERM: 'xterm-256color',
  SHELL: '/usr/local/bin/bash',
  USER: 'maciej',
  PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin',
  PWD: '/Users/maciej',
  EDITOR: 'vim',
  SHLVL: '1',
  HOME: '/Users/maciej',
  LOGNAME: 'maciej',
  _: '/usr/local/bin/node'
} 

可以修改此对象,但此类修改不会反映在 Node.js 进程之外,或反映到其他 Worker 线程(除非显示请求)。换句话说,以下示例将不起作用:

¥It is possible to modify this object, but such modifications will not be reflected outside the Node.js process, or (unless explicitly requested) to other Worker threads. In other words, the following example would not work:

node -e 'process.env.foo = "bar"' && echo $foo 

但是以下示例则将起作用:

¥While the following will:

import { env } from 'node:process';

env.foo = 'bar';
console.log(env.foo);const { env } = require('node:process');

env.foo = 'bar';
console.log(env.foo);

process.env 上分配属性会将值隐式转换为字符串。此行为已弃用。当值不是字符串、数字或布尔值时,Node.js 的未来版本可能会抛出错误。

¥Assigning a property on process.env will implicitly convert the value to a string. This behavior is deprecated. Future versions of Node.js may throw an error when the value is not a string, number, or boolean.

import { env } from 'node:process';

env.test = null;
console.log(env.test);
// => 'null'
env.test = undefined;
console.log(env.test);
// => 'undefined'const { env } = require('node:process');

env.test = null;
console.log(env.test);
// => 'null'
env.test = undefined;
console.log(env.test);
// => 'undefined'

使用 deleteprocess.env 中删除属性。

¥Use delete to delete a property from process.env.

import { env } from 'node:process';

env.TEST = 1;
delete env.TEST;
console.log(env.TEST);
// => undefinedconst { env } = require('node:process');

env.TEST = 1;
delete env.TEST;
console.log(env.TEST);
// => undefined

在 Windows 操作系统上,环境变量不区分大小写。

¥On Windows operating systems, environment variables are case-insensitive.

import { env } from 'node:process';

env.TEST = 1;
console.log(env.test);
// => 1const { env } = require('node:process');

env.TEST = 1;
console.log(env.test);
// => 1

除非在创建 Worker 实例时显式地指定,否则每个 Worker 线程都有自己的 process.env 副本,基于其父线程的 process.env,或任何指定为 Worker 构造函数的 env 选项。对 process.env 的更改不会跨 Worker 线程可见,只有主线程可以进行对操作系统或原生插件可见的更改。在 Windows 上,与主线程不同,Worker 实例上的 process.env 副本以区分大小写的方式运行。

¥Unless explicitly specified when creating a Worker instance, each Worker thread has its own copy of process.env, based on its parent thread's process.env, or whatever was specified as the env option to the Worker constructor. Changes to process.env will not be visible across Worker threads, and only the main thread can make changes that are visible to the operating system or to native add-ons. On Windows, a copy of process.env on a Worker instance operates in a case-sensitive manner unlike the main thread.

process.execArgv#

process.execArgv 属性返回 Node.js 进程启动时传入的一组特定于 Node.js 的命令行选项。这些选项不会出现在 process.argv 属性返回的数组中,也不包括 Node.js 可执行文件、脚本名称或脚本名称后面的任何选项。这些选项可用于衍生与父进程具有相同执行环境的子进程。

¥The process.execArgv property returns the set of Node.js-specific command-line options passed when the Node.js process was launched. These options do not appear in the array returned by the process.argv property, and do not include the Node.js executable, the name of the script, or any options following the script name. These options are useful in order to spawn child processes with the same execution environment as the parent.

node --icu-data-dir=./foo --require ./bar.js script.js --version 

process.execArgv 的结果:

¥Results in process.execArgv:

["--icu-data-dir=./foo", "--require", "./bar.js"] 

process.argv 的结果:

¥And process.argv:

['/usr/local/bin/node', 'script.js', '--version'] 

有关具有此属性的工作线程的详细行为,请参阅 Worker 构造函数

¥Refer to Worker constructor for the detailed behavior of worker threads with this property.

process.execPath#

process.execPath 属性返回启动 Node.js 进程的可执行文件的绝对路径名。符号链接(如果有)会被解析。

¥The process.execPath property returns the absolute pathname of the executable that started the Node.js process. Symbolic links, if any, are resolved.

'/usr/local/bin/node' 

process.exit([code])#

process.exit() 方法指示 Node.js 以 code 的退出状态同步终止进程。如果省略 code,则退出使用 'success' 代码 0process.exitCode 的值(如果已设置)。直到所有 'exit' 事件监听器都被调用,Node.js 才会终止。

¥The process.exit() method instructs Node.js to terminate the process synchronously with an exit status of code. If code is omitted, exit uses either the 'success' code 0 or the value of process.exitCode if it has been set. Node.js will not terminate until all the 'exit' event listeners are called.

要使用 'failure' 代码退出:

¥To exit with a 'failure' code:

import { exit } from 'node:process';

exit(1);const { exit } = require('node:process');

exit(1);

执行 Node.js 的 shell 应该看到退出码为 1

¥The shell that executed Node.js should see the exit code as 1.

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

¥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.

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

¥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.

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

¥For instance, the following example illustrates a misuse of the process.exit() method that could lead to data printed to stdout being truncated and lost:

import { exit } from 'node:process';

// This is an example of what *not* to do:
if (someConditionNotMet()) {
  printUsageToStdout();
  exit(1);
}const { exit } = require('node:process');

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

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

¥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.

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

¥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:

import process from 'node:process';

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

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

如果由于错误情况需要终止 Node.js 进程,则抛出未捕获的错误并允许进程相应地终止比调用 process.exit() 更安全。

¥If it is necessary to terminate the Node.js process due to an error condition, throwing an uncaught error and allowing the process to terminate accordingly is safer than calling process.exit().

Worker 线程中,该函数停止当前线程而不是当前进程。

¥In Worker threads, this function stops the current thread rather than the current process.

process.exitCode#

当进程正常退出或通过 process.exit() 退出而不指定代码时,将作为进程退出码的数字。

¥A number which will be the process exit code, when the process either exits gracefully, or is exited via process.exit() without specifying a code.

将代码指定为 process.exit(code) 将覆盖 process.exitCode 的任何先前设置。

¥Specifying a code to process.exit(code) will override any previous setting of process.exitCode.

process.features.cached_builtins#

如果当前 Node.js 构建正在缓存内置模块,则布尔值为 true

¥A boolean value that is true if the current Node.js build is caching builtin modules.

process.features.debug#

如果当前 Node.js 构建是调试构建,则布尔值为 true

¥A boolean value that is true if the current Node.js build is a debug build.

process.features.inspector#

如果当前 Node.js 构建包含检查器,则布尔值为 true

¥A boolean value that is true if the current Node.js build includes the inspector.

process.features.ipv6#

如果当前 Node.js 构建包含对 IPv6 的支持,则布尔值为 true

¥A boolean value that is true if the current Node.js build includes support for IPv6.

process.features.require_module#

如果当前 Node.js 构建支持 使用 require() 加载 ECMAScript 模块,则布尔值为 true

¥A boolean value that is true if the current Node.js build supports loading ECMAScript modules using require().

process.features.tls#

如果当前 Node.js 构建包含对 TLS 的支持,则布尔值为 true

¥A boolean value that is true if the current Node.js build includes support for TLS.

process.features.tls_alpn#

如果当前 Node.js 构建包含对 TLS 中的 ALPN 的支持,则布尔值为 true

¥A boolean value that is true if the current Node.js build includes support for ALPN in TLS.

process.features.tls_ocsp#

如果当前 Node.js 构建包含对 TLS 中的 OCSP 的支持,则布尔值为 true

¥A boolean value that is true if the current Node.js build includes support for OCSP in TLS.

process.features.tls_sni#

如果当前 Node.js 构建包含对 TLS 中的 SNI 的支持,则布尔值为 true

¥A boolean value that is true if the current Node.js build includes support for SNI in TLS.

process.features.typescript#

稳定性: 1.0 - 早期开发

¥Stability: 1.0 - Early development

如果 Node.js 使用 --experimental-strip-types 运行,则值为 "strip";如果 Node.js 使用 --experimental-transform-types 运行,则值为 "transform";否则为 false

¥A value that is "strip" if Node.js is run with --experimental-strip-types, "transform" if Node.js is run with --experimental-transform-types, and false otherwise.

process.features.uv#

如果当前 Node.js 构建包含对 libuv 的支持,则布尔值为 true。由于目前无法在没有 libuv 的情况下构建 Node.js,因此此值始终为 true

¥A boolean value that is true if the current Node.js build includes support for libuv. Since it's currently not possible to build Node.js without libuv, this value is always true.

process.finalization.register(ref, callback)#

稳定性: 1.1 - 积极开发

¥Stability: 1.1 - Active Development

  • ref <Object> | <Function> 对正在跟踪的资源的引用。

    ¥ref <Object> | <Function> The reference to the resource that is being tracked.

  • callback <Function> 资源最终确定后要调用的回调函数。

    ¥callback <Function> The callback function to be called when the resource is finalized.

    • ref <Object> | <Function> 对正在跟踪的资源的引用。

      ¥ref <Object> | <Function> The reference to the resource that is being tracked.

    • event <string> 触发最终确定的事件。默认为 'exit'。

      ¥event <string> The event that triggered the finalization. Defaults to 'exit'.

此函数注册一个回调,如果 ref 对象未被垃圾收集,则在进程触发 exit 事件时调用该回调。如果在触发 exit 事件之前对象 ref 被垃圾收集,则回调将从终止注册表中删除,并且在进程退出时不会调用它。

¥This function registers a callback to be called when the process emits the exit event if the ref object was not garbage collected. If the object ref was garbage collected before the exit event is emitted, the callback will be removed from the finalization registry, and it will not be called on process exit.

在回调中,你可以释放 ref 对象分配的资源。请注意,应用于 beforeExit 事件的所有限制也适用于 callback 函数,这意味着在特殊情况下可能不会调用回调。

¥Inside the callback you can release the resources allocated by the ref object. Be aware that all limitations applied to the beforeExit event are also applied to the callback function, this means that there is a possibility that the callback will not be called under special circumstances.

此功能的想法是帮助你在启动进程退出时释放资源,但如果不再使用对象,也可以让对象被垃圾回收。

¥The idea of ​​this function is to help you free up resources when the starts process exiting, but also let the object be garbage collected if it is no longer being used.

例如:你可以注册一个包含缓冲区的对象,你希望确保在进程退出时释放该缓冲区,但如果在进程退出之前对对象进行垃圾收集,则我们不再需要释放缓冲区,因此在这种情况下,我们只需从终止注册表中删除回调即可。

¥Eg: you can register an object that contains a buffer, you want to make sure that buffer is released when the process exit, but if the object is garbage collected before the process exit, we no longer need to release the buffer, so in this case we just remove the callback from the finalization registry.

const { finalization } = require('node:process');

// Please make sure that the function passed to finalization.register()
// does not create a closure around unnecessary objects.
function onFinalize(obj, event) {
  // You can do whatever you want with the object
  obj.dispose();
}

function setup() {
  // This object can be safely garbage collected,
  // and the resulting shutdown function will not be called.
  // There are no leaks.
  const myDisposableObject = {
    dispose() {
      // Free your resources synchronously
    },
  };

  finalization.register(myDisposableObject, onFinalize);
}

setup();import { finalization } from 'node:process';

// Please make sure that the function passed to finalization.register()
// does not create a closure around unnecessary objects.
function onFinalize(obj, event) {
  // You can do whatever you want with the object
  obj.dispose();
}

function setup() {
  // This object can be safely garbage collected,
  // and the resulting shutdown function will not be called.
  // There are no leaks.
  const myDisposableObject = {
    dispose() {
      // Free your resources synchronously
    },
  };

  finalization.register(myDisposableObject, onFinalize);
}

setup();

上面的代码依赖于以下假设:

¥The code above relies on the following assumptions:

  • 避免使用箭头函数

    ¥arrow functions are avoided

  • 建议将常规函数放在全局上下文(根)内

    ¥regular functions are recommended to be within the global context (root)

常规函数可以引用 obj 所在的上下文,使 obj 不可垃圾回收。

¥Regular functions could reference the context where the obj lives, making the obj not garbage collectible.

箭头函数将保存前一个上下文。例如,考虑:

¥Arrow functions will hold the previous context. Consider, for example:

class Test {
  constructor() {
    finalization.register(this, (ref) => ref.dispose());

    // even something like this is highly discouraged
    // finalization.register(this, () => this.dispose());
   }
   dispose() {}
} 

此对象不太可能(并非不可能)被垃圾收集,但如果没有,则在调用 process.exit 时将调用 dispose

¥It is very unlikely (not impossible) that this object will be garbage collected, but if it is not, dispose will be called when process.exit is called.

请小心并避免依赖此功能来处理关键资源,因为不能保证在任何情况下都会调用回调。

¥Be careful and avoid relying on this feature for the disposal of critical resources, as it is not guaranteed that the callback will be called under all circumstances.

process.finalization.registerBeforeExit(ref, callback)#

稳定性: 1.1 - 积极开发

¥Stability: 1.1 - Active Development

  • ref <Object> | <Function> 对正在跟踪的资源的引用。

    ¥ref <Object> | <Function> The reference to the resource that is being tracked.

  • callback <Function> 资源最终确定后要调用的回调函数。

    ¥callback <Function> The callback function to be called when the resource is finalized.

    • ref <Object> | <Function> 对正在跟踪的资源的引用。

      ¥ref <Object> | <Function> The reference to the resource that is being tracked.

    • event <string> 触发最终确定的事件。默认为 'beforeExit'。

      ¥event <string> The event that triggered the finalization. Defaults to 'beforeExit'.

此函数的行为与 register 完全相同,不同之处在于,如果 ref 对象未被垃圾收集,则在进程触发 beforeExit 事件时将调用回调。

¥This function behaves exactly like the register, except that the callback will be called when the process emits the beforeExit event if ref object was not garbage collected.

请注意,应用于 beforeExit 事件的所有限制也适用于 callback 函数,这意味着在特殊情况下可能不会调用回调。

¥Be aware that all limitations applied to the beforeExit event are also applied to the callback function, this means that there is a possibility that the callback will not be called under special circumstances.

process.finalization.unregister(ref)#

稳定性: 1.1 - 积极开发

¥Stability: 1.1 - Active Development

此函数从最终注册表中删除对象的注册,因此将不再调用回调。

¥This function remove the register of the object from the finalization registry, so the callback will not be called anymore.

const { finalization } = require('node:process');

// Please make sure that the function passed to finalization.register()
// does not create a closure around unnecessary objects.
function onFinalize(obj, event) {
  // You can do whatever you want with the object
  obj.dispose();
}

function setup() {
  // This object can be safely garbage collected,
  // and the resulting shutdown function will not be called.
  // There are no leaks.
  const myDisposableObject = {
    dispose() {
      // Free your resources synchronously
    },
  };

  finalization.register(myDisposableObject, onFinalize);

  // Do something

  myDisposableObject.dispose();
  finalization.unregister(myDisposableObject);
}

setup();import { finalization } from 'node:process';

// Please make sure that the function passed to finalization.register()
// does not create a closure around unnecessary objects.
function onFinalize(obj, event) {
  // You can do whatever you want with the object
  obj.dispose();
}

function setup() {
  // This object can be safely garbage collected,
  // and the resulting shutdown function will not be called.
  // There are no leaks.
  const myDisposableObject = {
    dispose() {
      // Free your resources synchronously
    },
  };

  // Please make sure that the function passed to finalization.register()
  // does not create a closure around unnecessary objects.
  function onFinalize(obj, event) {
    // You can do whatever you want with the object
    obj.dispose();
  }

  finalization.register(myDisposableObject, onFinalize);

  // Do something

  myDisposableObject.dispose();
  finalization.unregister(myDisposableObject);
}

setup();

process.getActiveResourcesInfo()#

稳定性: 1 - 实验性的

¥Stability: 1 - Experimental

process.getActiveResourcesInfo() 方法返回字符串数组,其中包含当前保持事件循环活动的活动资源的类型。

¥The process.getActiveResourcesInfo() method returns an array of strings containing the types of the active resources that are currently keeping the event loop alive.

import { getActiveResourcesInfo } from 'node:process';
import { setTimeout } from 'node:timers';

console.log('Before:', getActiveResourcesInfo());
setTimeout(() => {}, 1000);
console.log('After:', getActiveResourcesInfo());
// Prints:
//   Before: [ 'CloseReq', 'TTYWrap', 'TTYWrap', 'TTYWrap' ]
//   After: [ 'CloseReq', 'TTYWrap', 'TTYWrap', 'TTYWrap', 'Timeout' ]const { getActiveResourcesInfo } = require('node:process');
const { setTimeout } = require('node:timers');

console.log('Before:', getActiveResourcesInfo());
setTimeout(() => {}, 1000);
console.log('After:', getActiveResourcesInfo());
// Prints:
//   Before: [ 'TTYWrap', 'TTYWrap', 'TTYWrap' ]
//   After: [ 'TTYWrap', 'TTYWrap', 'TTYWrap', 'Timeout' ]

process.getBuiltinModule(id)#

process.getBuiltinModule(id) 提供了一种在全局可用函数中加载内置模块的方法。需要支持其他环境的 ES 模块可以使用它来有条件地加载在 Node.js 中运行时内置的 Node.js,而不必处理 import 在非 Node.js 环境中可能抛出的解析错误,也不必使用动态 import() 将模块转换为异步模块,或将同步 API 转换为异步 API。

¥process.getBuiltinModule(id) provides a way to load built-in modules in a globally available function. ES Modules that need to support other environments can use it to conditionally load a Node.js built-in when it is run in Node.js, without having to deal with the resolution error that can be thrown by import in a non-Node.js environment or having to use dynamic import() which either turns the module into an asynchronous module, or turns a synchronous API into an asynchronous one.

if (globalThis.process?.getBuiltinModule) {
  // Run in Node.js, use the Node.js fs module.
  const fs = globalThis.process.getBuiltinModule('fs');
  // If `require()` is needed to load user-modules, use createRequire()
  const module = globalThis.process.getBuiltinModule('module');
  const require = module.createRequire(import.meta.url);
  const foo = require('foo');
} 

如果 id 指定当前 Node.js 进程中可用的内置模块,则 process.getBuiltinModule(id) 方法返回相应的内置模块。如果 id 不对应任何内置模块,则返回 undefined

¥If id specifies a built-in module available in the current Node.js process, process.getBuiltinModule(id) method returns the corresponding built-in module. If id does not correspond to any built-in module, undefined is returned.

process.getBuiltinModule(id) 接受 module.isBuiltin(id) 识别的内置模块 ID。某些内置模块必须使用 node: 前缀加载,请参阅 使用强制 node: 前缀的内置模块。即使用户修改 require.cache 以使 require(id) 返回其他内容,process.getBuiltinModule(id) 返回的引用也始终指向与 id 对应的内置模块。

¥process.getBuiltinModule(id) accepts built-in module IDs that are recognized by module.isBuiltin(id). Some built-in modules must be loaded with the node: prefix, see built-in modules with mandatory node: prefix. The references returned by process.getBuiltinModule(id) always point to the built-in module corresponding to id even if users modify require.cache so that require(id) returns something else.

process.getegid()#

process.getegid() 方法返回 Node.js 进程的数字有效群组标识。(请参阅 getegid(2)。)

¥The process.getegid() method returns the numerical effective group identity of the Node.js process. (See getegid(2).)

import process from 'node:process';

if (process.getegid) {
  console.log(`Current gid: ${process.getegid()}`);
}const process = require('node:process');

if (process.getegid) {
  console.log(`Current gid: ${process.getegid()}`);
}

此功能仅适用于 POSIX 平台(即不适用于 Windows 或安卓)。

¥This function is only available on POSIX platforms (i.e. not Windows or Android).

process.geteuid()#

process.geteuid() 方法返回进程的数字有效用户身份。(请参阅 geteuid(2)。)

¥The process.geteuid() method returns the numerical effective user identity of the process. (See geteuid(2).)

import process from 'node:process';

if (process.geteuid) {
  console.log(`Current uid: ${process.geteuid()}`);
}const process = require('node:process');

if (process.geteuid) {
  console.log(`Current uid: ${process.geteuid()}`);
}

此功能仅适用于 POSIX 平台(即不适用于 Windows 或安卓)。

¥This function is only available on POSIX platforms (i.e. not Windows or Android).

process.getgid()#

process.getgid() 方法返回进程的数字群组标识。(请参阅 getgid(2)。)

¥The process.getgid() method returns the numerical group identity of the process. (See getgid(2).)

import process from 'node:process';

if (process.getgid) {
  console.log(`Current gid: ${process.getgid()}`);
}const process = require('node:process');

if (process.getgid) {
  console.log(`Current gid: ${process.getgid()}`);
}

此功能仅适用于 POSIX 平台(即不适用于 Windows 或安卓)。

¥This function is only available on POSIX platforms (i.e. not Windows or Android).

process.getgroups()#

process.getgroups() 方法返回带有补充组 ID 的数组。POSIX 不指定是否包含有效组 ID,但 Node.js 确保它始终包含。

¥The process.getgroups() method returns an array with the supplementary group IDs. POSIX leaves it unspecified if the effective group ID is included but Node.js ensures it always is.

import process from 'node:process';

if (process.getgroups) {
  console.log(process.getgroups()); // [ 16, 21, 297 ]
}const process = require('node:process');

if (process.getgroups) {
  console.log(process.getgroups()); // [ 16, 21, 297 ]
}

此功能仅适用于 POSIX 平台(即不适用于 Windows 或安卓)。

¥This function is only available on POSIX platforms (i.e. not Windows or Android).

process.getuid()#

process.getuid() 方法返回进程的数字用户标识。(请参阅 getuid(2)。)

¥The process.getuid() method returns the numeric user identity of the process. (See getuid(2).)

import process from 'node:process';

if (process.getuid) {
  console.log(`Current uid: ${process.getuid()}`);
}const process = require('node:process');

if (process.getuid) {
  console.log(`Current uid: ${process.getuid()}`);
}

此功能仅适用于 POSIX 平台(即不适用于 Windows 或安卓)。

¥This function is only available on POSIX platforms (i.e. not Windows or Android).

process.hasUncaughtExceptionCaptureCallback()#

指示是否已使用 process.setUncaughtExceptionCaptureCallback() 设置回调。

¥Indicates whether a callback has been set using process.setUncaughtExceptionCaptureCallback().

process.hrtime([time])#

稳定性: 3 - 旧版的。改用 process.hrtime.bigint()

¥Stability: 3 - Legacy. Use process.hrtime.bigint() instead.

这是 process.hrtime.bigint() 在 JavaScript 中引入 bigint 之前的旧版本。

¥This is the legacy version of process.hrtime.bigint() before bigint was introduced in JavaScript.

process.hrtime() 方法在 [seconds, nanoseconds] 元组 Array 中返回当前高解析度实时,其中 nanoseconds 是无法以秒精度表示的实时剩余部分。

¥The process.hrtime() method returns the current high-resolution real time in a [seconds, nanoseconds] tuple Array, where nanoseconds is the remaining part of the real time that can't be represented in second precision.

time 是可选参数,它必须是先前 process.hrtime() 调用 diff 与当前时间的结果。如果传入的参数不是元组 Array,则会抛出 TypeError。传入用户定义的数组而不是先前调用 process.hrtime() 的结果将导致未定义的行为。

¥time is an optional parameter that must be the result of a previous process.hrtime() call to diff with the current time. If the parameter passed in is not a tuple Array, a TypeError will be thrown. Passing in a user-defined array instead of the result of a previous call to process.hrtime() will lead to undefined behavior.

这些时间相对于过去的任意时间,与一天中的时间无关,因此不受时钟漂移的影响。主要用途是测量间隔之间的性能:

¥These times are relative to an arbitrary time in the past, and not related to the time of day and therefore not subject to clock drift. The primary use is for measuring performance between intervals:

import { hrtime } from 'node:process';

const NS_PER_SEC = 1e9;
const time = hrtime();
// [ 1800216, 25 ]

setTimeout(() => {
  const diff = hrtime(time);
  // [ 1, 552 ]

  console.log(`Benchmark took ${diff[0] * NS_PER_SEC + diff[1]} nanoseconds`);
  // Benchmark took 1000000552 nanoseconds
}, 1000);const { hrtime } = require('node:process');

const NS_PER_SEC = 1e9;
const time = hrtime();
// [ 1800216, 25 ]

setTimeout(() => {
  const diff = hrtime(time);
  // [ 1, 552 ]

  console.log(`Benchmark took ${diff[0] * NS_PER_SEC + diff[1]} nanoseconds`);
  // Benchmark took 1000000552 nanoseconds
}, 1000);

process.hrtime.bigint()#

process.hrtime() 方法的 bigint 版本以纳秒为单位返回当前高解析度实时作为 bigint

¥The bigint version of the process.hrtime() method returning the current high-resolution real time in nanoseconds as a bigint.

process.hrtime() 不同,它不支持额外的 time 参数,因为差异可以直接通过减去两个 bigint 来计算。

¥Unlike process.hrtime(), it does not support an additional time argument since the difference can just be computed directly by subtraction of the two bigints.

import { hrtime } from 'node:process';

const start = hrtime.bigint();
// 191051479007711n

setTimeout(() => {
  const end = hrtime.bigint();
  // 191052633396993n

  console.log(`Benchmark took ${end - start} nanoseconds`);
  // Benchmark took 1154389282 nanoseconds
}, 1000);const { hrtime } = require('node:process');

const start = hrtime.bigint();
// 191051479007711n

setTimeout(() => {
  const end = hrtime.bigint();
  // 191052633396993n

  console.log(`Benchmark took ${end - start} nanoseconds`);
  // Benchmark took 1154389282 nanoseconds
}, 1000);

process.initgroups(user, extraGroup)#

process.initgroups() 方法读取 /etc/group 文件并使用用户所属的所有组初始化组访问列表。这是一个特权操作,要求 Node.js 进程具有 root 访问权限或 CAP_SETGID 能力。

¥The process.initgroups() method reads the /etc/group file and initializes the group access list, using all groups of which the user is a member. This is a privileged operation that requires that the Node.js process either have root access or the CAP_SETGID capability.

删除权限时要小心:

¥Use care when dropping privileges:

import { getgroups, initgroups, setgid } from 'node:process';

console.log(getgroups());         // [ 0 ]
initgroups('nodeuser', 1000);     // switch user
console.log(getgroups());         // [ 27, 30, 46, 1000, 0 ]
setgid(1000);                     // drop root gid
console.log(getgroups());         // [ 27, 30, 46, 1000 ]const { getgroups, initgroups, setgid } = require('node:process');

console.log(getgroups());         // [ 0 ]
initgroups('nodeuser', 1000);     // switch user
console.log(getgroups());         // [ 27, 30, 46, 1000, 0 ]
setgid(1000);                     // drop root gid
console.log(getgroups());         // [ 27, 30, 46, 1000 ]

此功能仅适用于 POSIX 平台(即不适用于 Windows 或安卓)。此特性在 Worker 线程中不可用。

¥This function is only available on POSIX platforms (i.e. not Windows or Android). This feature is not available in Worker threads.

process.kill(pid[, signal])#

  • pid <number> 进程标识

    ¥pid <number> A process ID

  • signal <string> | <number> 要发送的信号,可以是字符串或数字。默认值:'SIGTERM'

    ¥signal <string> | <number> The signal to send, either as a string or number. Default: 'SIGTERM'.

process.kill() 方法将 signal 发送到由 pid 标识的进程。

¥The process.kill() method sends the signal to the process identified by pid.

信号名称是字符串,例如 'SIGINT''SIGHUP'。有关详细信息,请参阅 信号事件kill(2)

¥Signal names are strings such as 'SIGINT' or 'SIGHUP'. See Signal Events and kill(2) for more information.

如果目标 pid 不存在,则此方法将抛出错误。作为特殊情况,可以使用信号 0 来测试进程是否存在。如果使用 pid 来杀死进程组,则 Windows 平台将抛出错误。

¥This method will throw an error if the target pid does not exist. As a special case, a signal of 0 can be used to test for the existence of a process. Windows platforms will throw an error if the pid is used to kill a process group.

尽管此函数的名字是 process.kill(),但它实际上只是信号发送者,就像 kill 系统调用。发送的信号可能会做其他事情而不是杀死目标进程。

¥Even though the name of this function is process.kill(), it is really just a signal sender, like the kill system call. The signal sent may do something other than kill the target process.

import process, { kill } from 'node:process';

process.on('SIGHUP', () => {
  console.log('Got SIGHUP signal.');
});

setTimeout(() => {
  console.log('Exiting.');
  process.exit(0);
}, 100);

kill(process.pid, 'SIGHUP');const process = require('node:process');

process.on('SIGHUP', () => {
  console.log('Got SIGHUP signal.');
});

setTimeout(() => {
  console.log('Exiting.');
  process.exit(0);
}, 100);

process.kill(process.pid, 'SIGHUP');

当 Node.js 进程收到 SIGUSR1 时,Node.js 将启动调试器。参见 信号事件

¥When SIGUSR1 is received by a Node.js process, Node.js will start the debugger. See Signal Events.

process.loadEnvFile(path)#

稳定性: 1.1 - 积极开发

¥Stability: 1.1 - Active development

.env 文件加载到 process.env 中。在 .env 文件中使用 NODE_OPTIONS 不会对 Node.js 产生任何影响。

¥Loads the .env file into process.env. Usage of NODE_OPTIONS in the .env file will not have any effect on Node.js.

const { loadEnvFile } = require('node:process');
loadEnvFile();import { loadEnvFile } from 'node:process';
loadEnvFile();

process.mainModule#

稳定性: 0 - 已弃用:改用 require.main

¥Stability: 0 - Deprecated: Use require.main instead.

process.mainModule 属性提供了另一种检索 require.main 的方法。不同之处在于,如果主模块在运行时发生更改,则 require.main 可能仍会引用更改发生前所需模块中的原始主模块。通常,可以安全地假设两者指的是同一个模块。

¥The process.mainModule property provides an alternative way of retrieving require.main. The difference is that if the main module changes at runtime, require.main may still refer to the original main module in modules that were required before the change occurred. Generally, it's safe to assume that the two refer to the same module.

require.main 一样,如果没有入口脚本,则 process.mainModule 将是 undefined

¥As with require.main, process.mainModule will be undefined if there is no entry script.

process.memoryUsage()#

返回描述 Node.js 进程的内存使用量(以字节为单位)的对象。

¥Returns an object describing the memory usage of the Node.js process measured in bytes.

import { memoryUsage } from 'node:process';

console.log(memoryUsage());
// Prints:
// {
//  rss: 4935680,
//  heapTotal: 1826816,
//  heapUsed: 650472,
//  external: 49879,
//  arrayBuffers: 9386
// }const { memoryUsage } = require('node:process');

console.log(memoryUsage());
// Prints:
// {
//  rss: 4935680,
//  heapTotal: 1826816,
//  heapUsed: 650472,
//  external: 49879,
//  arrayBuffers: 9386
// }
  • heapTotalheapUsed 指的是 V8 的内存使用量。

    ¥heapTotal and heapUsed refer to V8's memory usage.

  • external 指的是绑定到 V8 管理的 JavaScript 对象的 C++ 对象的内存使用量。

    ¥external refers to the memory usage of C++ objects bound to JavaScript objects managed by V8.

  • rss,常驻集大小,是进程在主内存设备(即总分配内存的子集)中占用的空间量,包括所有 C++ 和 JavaScript 对象和代码。

    ¥rss, Resident Set Size, is the amount of space occupied in the main memory device (that is a subset of the total allocated memory) for the process, including all C++ and JavaScript objects and code.

  • arrayBuffers 是指为 ArrayBufferSharedArrayBuffer 分配的内存,包括所有 Node.js Buffer。这也包含在 external 值中。当 Node.js 用作嵌入式库时,此值可能是 0,因为在这种情况下可能不会跟踪 ArrayBuffer 的分配。

    ¥arrayBuffers refers to memory allocated for ArrayBuffers and SharedArrayBuffers, including all Node.js Buffers. This is also included in the external value. When Node.js is used as an embedded library, this value may be 0 because allocations for ArrayBuffers may not be tracked in that case.

当使用 Worker 线程时,则 rss 将是对整个进程都有效的值,而其他字段仅涉及当前线程。

¥When using Worker threads, rss will be a value that is valid for the entire process, while the other fields will only refer to the current thread.

process.memoryUsage() 方法遍历每个页面以收集有关内存使用情况的信息,这可能会根据程序内存分配而变慢。

¥The process.memoryUsage() method iterates over each page to gather information about memory usage which might be slow depending on the program memory allocations.

process.memoryUsage.rss()#

process.memoryUsage.rss() 方法返回以字节为单位表示驻留集大小的整数 (RSS)。

¥The process.memoryUsage.rss() method returns an integer representing the Resident Set Size (RSS) in bytes.

驻留集大小是进程在主内存设备(即总分配内存的子集)中占用的空间量,包括所有 C++ 和 JavaScript 对象和代码。

¥The Resident Set Size, is the amount of space occupied in the main memory device (that is a subset of the total allocated memory) for the process, including all C++ and JavaScript objects and code.

这与 process.memoryUsage() 提供的 rss 属性值相同,但 process.memoryUsage.rss() 更快。

¥This is the same value as the rss property provided by process.memoryUsage() but process.memoryUsage.rss() is faster.

import { memoryUsage } from 'node:process';

console.log(memoryUsage.rss());
// 35655680const { memoryUsage } = require('node:process');

console.log(memoryUsage.rss());
// 35655680

process.nextTick(callback[, ...args])#

稳定性: 3 - 旧版:改用 queueMicrotask()

¥Stability: 3 - Legacy: Use queueMicrotask() instead.

  • callback <Function>

  • ...args <any> 当调用 callback 时要传入的额外参数

    ¥...args <any> Additional arguments to pass when invoking the callback

process.nextTick()callback 添加到 "下一个滴答队列"。在 JavaScript 堆栈上的当前操作运行完成之后,且在允许事件循环继续之前,此队列将被完全排空。如果递归地调用 process.nextTick(),则可能会创建无限的循环。有关更多背景信息,请参阅 事件循环 指南。

¥process.nextTick() adds callback to the "next tick queue". This queue is fully drained after the current operation on the JavaScript stack runs to completion and before the event loop is allowed to continue. It's possible to create an infinite loop if one were to recursively call process.nextTick(). See the Event Loop guide for more background.

import { nextTick } from 'node:process';

console.log('start');
nextTick(() => {
  console.log('nextTick callback');
});
console.log('scheduled');
// Output:
// start
// scheduled
// nextTick callbackconst { nextTick } = require('node:process');

console.log('start');
nextTick(() => {
  console.log('nextTick callback');
});
console.log('scheduled');
// Output:
// start
// scheduled
// nextTick callback

这在开发 API 时很重要,以便让用户有机会在对象构建之后但在任何 I/O 发生之前分配事件处理程序:

¥This is important when developing APIs in order to give users the opportunity to assign event handlers after an object has been constructed but before any I/O has occurred:

import { nextTick } from 'node:process';

function MyThing(options) {
  this.setupOptions(options);

  nextTick(() => {
    this.startDoingStuff();
  });
}

const thing = new MyThing();
thing.getReadyForStuff();

// thing.startDoingStuff() gets called now, not before.const { nextTick } = require('node:process');

function MyThing(options) {
  this.setupOptions(options);

  nextTick(() => {
    this.startDoingStuff();
  });
}

const thing = new MyThing();
thing.getReadyForStuff();

// thing.startDoingStuff() gets called now, not before.

这对于要 100% 同步或 100% 异步的 API 非常重要。设想这个示例:

¥It is very important for APIs to be either 100% synchronous or 100% asynchronous. Consider this example:

// WARNING!  DO NOT USE!  BAD UNSAFE HAZARD!
function maybeSync(arg, cb) {
  if (arg) {
    cb();
    return;
  }

  fs.stat('file', cb);
} 

此 API 是危险的,因为在以下情况下:

¥This API is hazardous because in the following case:

const maybeTrue = Math.random() > 0.5;

maybeSync(maybeTrue, () => {
  foo();
});

bar(); 

并不清楚是先调用 foo() 还是 bar()

¥It is not clear whether foo() or bar() will be called first.

以下方法要好得多:

¥The following approach is much better:

import { nextTick } from 'node:process';

function definitelyAsync(arg, cb) {
  if (arg) {
    nextTick(cb);
    return;
  }

  fs.stat('file', cb);
}const { nextTick } = require('node:process');

function definitelyAsync(arg, cb) {
  if (arg) {
    nextTick(cb);
    return;
  }

  fs.stat('file', cb);
}

何时使用 queueMicrotask()process.nextTick()#

¥When to use queueMicrotask() vs. process.nextTick()

queueMicrotask() API 是 process.nextTick() 的替代方案,它还使用用于执行 then、catch 和 finally 处理程序的相同微任务队列来延迟函数的执行。在 Node.js 中,每次耗尽 "下一个滴答队列" 时,微任务队列都会立即耗尽。

¥The queueMicrotask() API is an alternative to process.nextTick() that also defers execution of a function using the same microtask queue used to execute the then, catch, and finally handlers of resolved promises. Within Node.js, every time the "next tick queue" is drained, the microtask queue is drained immediately after.

import { nextTick } from 'node:process';

Promise.resolve().then(() => console.log(2));
queueMicrotask(() => console.log(3));
nextTick(() => console.log(1));
// Output:
// 1
// 2
// 3const { nextTick } = require('node:process');

Promise.resolve().then(() => console.log(2));
queueMicrotask(() => console.log(3));
nextTick(() => console.log(1));
// Output:
// 1
// 2
// 3

对于大多数用户态用例,queueMicrotask() API 提供了一种可移植且可靠的延迟执行机制,该机制适用于多个 JavaScript 平台环境,应该优于 process.nextTick()。在简单的场景中,queueMicrotask() 可以直接替代 process.nextTick()

¥For most userland use cases, the queueMicrotask() API provides a portable and reliable mechanism for deferring execution that works across multiple JavaScript platform environments and should be favored over process.nextTick(). In simple scenarios, queueMicrotask() can be a drop-in replacement for process.nextTick().

console.log('start');
queueMicrotask(() => {
  console.log('microtask callback');
});
console.log('scheduled');
// Output:
// start
// scheduled
// microtask callback 

两个 API 之间一个值得注意的区别是 process.nextTick() 允许指定额外值,这些值将在调用时作为参数传递给延迟函数。使用 queueMicrotask() 实现相同的结果需要使用闭包或绑定函数:

¥One note-worthy difference between the two APIs is that process.nextTick() allows specifying additional values that will be passed as arguments to the deferred function when it is called. Achieving the same result with queueMicrotask() requires using either a closure or a bound function:

function deferred(a, b) {
  console.log('microtask', a + b);
}

console.log('start');
queueMicrotask(deferred.bind(undefined, 1, 2));
console.log('scheduled');
// Output:
// start
// scheduled
// microtask 3 

从下一个滴答队列和微任务队列中引发的错误的处理方式存在细微差别。在排队的微任务回调中抛出的错误应该在可能的情况下在排队的回调中处理。如果不是,则可以使用 process.on('uncaughtException') 事件句柄来捕获和处理错误。

¥There are minor differences in the way errors raised from within the next tick queue and microtask queue are handled. Errors thrown within a queued microtask callback should be handled within the queued callback when possible. If they are not, the process.on('uncaughtException') event handler can be used to capture and handle the errors.

如有疑问,除非需要 process.nextTick() 的特定功能,否则请使用 queueMicrotask()

¥When in doubt, unless the specific capabilities of process.nextTick() are needed, use queueMicrotask().

process.noDeprecation#

process.noDeprecation 属性指示是否在当前 Node.js 进程上设置了 --no-deprecation 标志。有关此标志行为的更多信息,请参阅 'warning' 事件emitWarning() 方法 的文档。

¥The process.noDeprecation property indicates whether the --no-deprecation flag is set on the current Node.js process. See the documentation for the 'warning' event and the emitWarning() method for more information about this flag's behavior.

process.permission#

此 API 可通过 --experimental-permission 标志使用。

¥This API is available through the --experimental-permission flag.

process.permission 是一个对象,其方法用于管理当前进程的权限。权限模型 中提供了其他文档。

¥process.permission is an object whose methods are used to manage permissions for the current process. Additional documentation is available in the Permission Model.

process.permission.has(scope[, reference])#

验证进程是否能够访问给定的范围和引用。如果未提供引用,则假定为全局作用域,例如,process.permission.has('fs.read') 将检查进程是否具有所有文件系统读取权限。

¥Verifies that the process is able to access the given scope and reference. If no reference is provided, a global scope is assumed, for instance, process.permission.has('fs.read') will check if the process has ALL file system read permissions.

引用具有基于所提供范围的含义。例如,范围为文件系统时的引用表示文件和文件夹。

¥The reference has a meaning based on the provided scope. For example, the reference when the scope is File System means files and folders.

可用的范围是:

¥The available scopes are:

  • fs - 所有文件系统

    ¥fs - All File System

  • fs.read - 文件系统读取操作

    ¥fs.read - File System read operations

  • fs.write - 文件系统写操作

    ¥fs.write - File System write operations

  • child - 子进程生成操作

    ¥child - Child process spawning operations

  • worker - 工作线程生成操作

    ¥worker - Worker thread spawning operation

// Check if the process has permission to read the README file
process.permission.has('fs.read', './README.md');
// Check if the process has read permission operations
process.permission.has('fs.read'); 

process.pid#

process.pid 属性返回进程的 PID。

¥The process.pid property returns the PID of the process.

import { pid } from 'node:process';

console.log(`This process is pid ${pid}`);const { pid } = require('node:process');

console.log(`This process is pid ${pid}`);

process.platform#

process.platform 属性返回用于标识编译 Node.js 二进制文件的操作系统平台的字符串。

¥The process.platform property returns a string identifying the operating system platform for which the Node.js binary was compiled.

目前可能的值是:

¥Currently possible values are:

  • 'aix'

  • 'darwin'

  • 'freebsd'

  • 'linux'

  • 'openbsd'

  • 'sunos'

  • 'win32'

import { platform } from 'node:process';

console.log(`This platform is ${platform}`);const { platform } = require('node:process');

console.log(`This platform is ${platform}`);

如果 Node.js 是在安卓操作系统上构建的,则也可能返回值 'android'。但是,Android 支持 Node.js 是实验性的

¥The value 'android' may also be returned if the Node.js is built on the Android operating system. However, Android support in Node.js is experimental.

process.ppid#

process.ppid 属性返回当前进程的父进程的 PID。

¥The process.ppid property returns the PID of the parent of the current process.

import { ppid } from 'node:process';

console.log(`The parent process is pid ${ppid}`);const { ppid } = require('node:process');

console.log(`The parent process is pid ${ppid}`);

process.release#

process.release 属性返回 Object,其中包含与当前版本相关的元数据,包括源 tarball 和 headers-only tarball 的网址。

¥The process.release property returns an Object containing metadata related to the current release, including URLs for the source tarball and headers-only tarball.

process.release 包含以下属性:

¥process.release contains the following properties:

  • name <string> 始终为 'node' 的值。

    ¥name <string> A value that will always be 'node'.

  • sourceUrl <string> 指向包含当前版本源代码的 .tar.gz 文件的绝对 URL。

    ¥sourceUrl <string> an absolute URL pointing to a .tar.gz file containing the source code of the current release.

  • headersUrl <string> 指向仅包含当前版本的源头文件的 .tar.gz 文件的绝对 URL。该文件比完整的源文件小得多,可用于编译 Node.js 原生插件。

    ¥headersUrl<string> an absolute URL pointing to a .tar.gz file containing only the source header files for the current release. This file is significantly smaller than the full source file and can be used for compiling Node.js native add-ons.

  • libUrl <string> | <undefined> 指向与当前版本的体系结构和版本匹配的 node.lib 文件的绝对 URL。此文件用于编译 Node.js 原生插件。此属性仅存在于 Node.js 的 Windows 构建中,在所有其他平台上将不存在。

    ¥libUrl <string> | <undefined> an absolute URL pointing to a node.lib file matching the architecture and version of the current release. This file is used for compiling Node.js native add-ons. This property is only present on Windows builds of Node.js and will be missing on all other platforms.

  • lts <string> | <undefined> 标识此版本的 LTS 标签的字符串标签。此属性仅适用于 LTS 版本,对于所有其他版本类型(包括当前版本)为 undefined。有效值包括 LTS 版本代码名称(包括不再受支持的代码名称)。

    ¥lts <string> | <undefined> a string label identifying the LTS label for this release. This property only exists for LTS releases and is undefined for all other release types, including Current releases. Valid values include the LTS Release code names (including those that are no longer supported).

    • 以 14.15.0 开头的 14.x LTS 系列的 'Fermium'

      ¥'Fermium' for the 14.x LTS line beginning with 14.15.0.

    • 以 16.13.0 开头的 16.x LTS 系列的 'Gallium'

      ¥'Gallium' for the 16.x LTS line beginning with 16.13.0.

    • 'Hydrogen' 用于从 18.12.0 开始的 18.x LTS 行。对于其他 LTS 版本代号,请参见 Node.js 变更日志存档

      ¥'Hydrogen' for the 18.x LTS line beginning with 18.12.0. For other LTS Release code names, see Node.js Changelog Archive

{
  name: 'node',
  lts: 'Hydrogen',
  sourceUrl: 'https://nodejs.cn/download/release/v18.12.0/node-v18.12.0.tar.gz',
  headersUrl: 'https://nodejs.cn/download/release/v18.12.0/node-v18.12.0-headers.tar.gz',
  libUrl: 'https://nodejs.cn/download/release/v18.12.0/win-x64/node.lib'
} 

在源代码树的非发布版本的自定义构建中,可能只存在 name 属性。不应依赖附加属性的存在。

¥In custom builds from non-release versions of the source tree, only the name property may be present. The additional properties should not be relied upon to exist.

process.report#

process.report 是一个对象,其方法用于为当前进程生成诊断报告。报告文件 中提供了其他文档。

¥process.report is an object whose methods are used to generate diagnostic reports for the current process. Additional documentation is available in the report documentation.

process.report.compact#

以紧凑的单行 JSON 格式编写报告,与专为人类使用而设计的默认多行格式相比,日志处理系统更易于使用。

¥Write reports in a compact format, single-line JSON, more easily consumable by log processing systems than the default multi-line format designed for human consumption.

import { report } from 'node:process';

console.log(`Reports are compact? ${report.compact}`);const { report } = require('node:process');

console.log(`Reports are compact? ${report.compact}`);

process.report.directory#

写入报告的目录。默认值为空字符串,表示将报告写入 Node.js 进程的当前工作目录。

¥Directory where the report is written. The default value is the empty string, indicating that reports are written to the current working directory of the Node.js process.

import { report } from 'node:process';

console.log(`Report directory is ${report.directory}`);const { report } = require('node:process');

console.log(`Report directory is ${report.directory}`);

process.report.filename#

写入报告的文件名。如果设置为空字符串,则输出文件名将由时间戳、PID 和序列号组成。默认值为空字符串。

¥Filename where the report is written. If set to the empty string, the output filename will be comprised of a timestamp, PID, and sequence number. The default value is the empty string.

如果 process.report.filename 的值设置为 'stdout''stderr',则报告分别写入进程的 stdout 或 stderr。

¥If the value of process.report.filename is set to 'stdout' or 'stderr', the report is written to the stdout or stderr of the process respectively.

import { report } from 'node:process';

console.log(`Report filename is ${report.filename}`);const { report } = require('node:process');

console.log(`Report filename is ${report.filename}`);

process.report.getReport([err])#

  • err <Error> 用于报告 JavaScript 堆栈的自定义错误。

    ¥err <Error> A custom error used for reporting the JavaScript stack.

  • 返回:<Object>

    ¥Returns: <Object>

返回正在运行的进程的诊断报告的 JavaScript 对象表示形式。报告的 JavaScript 堆栈跟踪取自 err(如果存在)。

¥Returns a JavaScript Object representation of a diagnostic report for the running process. The report's JavaScript stack trace is taken from err, if present.

import { report } from 'node:process';
import util from 'node:util';

const data = report.getReport();
console.log(data.header.nodejsVersion);

// Similar to process.report.writeReport()
import fs from 'node:fs';
fs.writeFileSync('my-report.log', util.inspect(data), 'utf8');const { report } = require('node:process');
const util = require('node:util');

const data = report.getReport();
console.log(data.header.nodejsVersion);

// Similar to process.report.writeReport()
const fs = require('node:fs');
fs.writeFileSync('my-report.log', util.inspect(data), 'utf8');

报告文件 中提供了其他文档。

¥Additional documentation is available in the report documentation.

process.report.reportOnFatalError#

如果为 true,则会生成有关致命错误(例如内存不足错误或 C++ 断言失败)的诊断报告。

¥If true, a diagnostic report is generated on fatal errors, such as out of memory errors or failed C++ assertions.

import { report } from 'node:process';

console.log(`Report on fatal error: ${report.reportOnFatalError}`);const { report } = require('node:process');

console.log(`Report on fatal error: ${report.reportOnFatalError}`);

process.report.reportOnSignal#

如果为 true,则当进程接收到 process.report.signal 指定的信号时生成诊断报告。

¥If true, a diagnostic report is generated when the process receives the signal specified by process.report.signal.

import { report } from 'node:process';

console.log(`Report on signal: ${report.reportOnSignal}`);const { report } = require('node:process');

console.log(`Report on signal: ${report.reportOnSignal}`);

process.report.reportOnUncaughtException#

如果为 true,则针对未捕获的异常生成诊断报告。

¥If true, a diagnostic report is generated on uncaught exception.

import { report } from 'node:process';

console.log(`Report on exception: ${report.reportOnUncaughtException}`);const { report } = require('node:process');

console.log(`Report on exception: ${report.reportOnUncaughtException}`);

process.report.signal#

用于触发诊断报告创建的信号。默认为 'SIGUSR2'

¥The signal used to trigger the creation of a diagnostic report. Defaults to 'SIGUSR2'.

import { report } from 'node:process';

console.log(`Report signal: ${report.signal}`);const { report } = require('node:process');

console.log(`Report signal: ${report.signal}`);

process.report.writeReport([filename][, err])#

  • filename <string> 写入报告的文件的名称。这应该是相对路径,如果未指定,它将附加到 process.report.directory 中指定的目录或 Node.js 进程的当前工作目录。

    ¥filename <string> Name of the file where the report is written. This should be a relative path, that will be appended to the directory specified in process.report.directory, or the current working directory of the Node.js process, if unspecified.

  • err <Error> 用于报告 JavaScript 堆栈的自定义错误。

    ¥err <Error> A custom error used for reporting the JavaScript stack.

  • 返回:<string> 返回生成的报告的文件名。

    ¥Returns: <string> Returns the filename of the generated report.

将诊断报告写入文件。如果未提供 filename,则默认文件名包括日期、时间、PID 和序列号。报告的 JavaScript 堆栈跟踪取自 err(如果存在)。

¥Writes a diagnostic report to a file. If filename is not provided, the default filename includes the date, time, PID, and a sequence number. The report's JavaScript stack trace is taken from err, if present.

如果 filename 的值设置为 'stdout''stderr',则报告分别写入进程的 stdout 或 stderr。

¥If the value of filename is set to 'stdout' or 'stderr', the report is written to the stdout or stderr of the process respectively.

import { report } from 'node:process';

report.writeReport();const { report } = require('node:process');

report.writeReport();

报告文件 中提供了其他文档。

¥Additional documentation is available in the report documentation.

process.resourceUsage()#

  • 返回:<Object> 当前进程的资源使用情况。所有这些值都来自返回 uv_rusage_t 结构uv_getrusage 调用。

    ¥Returns: <Object> the resource usage for the current process. All of these values come from the uv_getrusage call which returns a uv_rusage_t struct.

    • userCPUTime <integer> 映射到以微秒计算的 ru_utime。它与 process.cpuUsage().user 的值相同。

      ¥userCPUTime <integer> maps to ru_utime computed in microseconds. It is the same value as process.cpuUsage().user.

    • systemCPUTime <integer> 映射到以微秒计算的 ru_stime。它与 process.cpuUsage().system 的值相同。

      ¥systemCPUTime <integer> maps to ru_stime computed in microseconds. It is the same value as process.cpuUsage().system.

    • maxRSS <integer> 映射到 ru_maxrss,这是使用的最大驻留集大小(以千字节为单位)。

      ¥maxRSS <integer> maps to ru_maxrss which is the maximum resident set size used in kilobytes.

    • sharedMemorySize <integer> 映射到 ru_ixrss 但不受任何平台支持。

      ¥sharedMemorySize <integer> maps to ru_ixrss but is not supported by any platform.

    • unsharedDataSize <integer> 映射到 ru_idrss 但不受任何平台支持。

      ¥unsharedDataSize <integer> maps to ru_idrss but is not supported by any platform.

    • unsharedStackSize <integer> 映射到 ru_isrss 但不受任何平台支持。

      ¥unsharedStackSize <integer> maps to ru_isrss but is not supported by any platform.

    • minorPageFault <integer> 映射到 ru_minflt,它是进程的次要页面错误数,请参阅 这篇文章了解更多详情

      ¥minorPageFault <integer> maps to ru_minflt which is the number of minor page faults for the process, see this article for more details.

    • majorPageFault <integer> 映射到 ru_majflt,这是进程的主要页面错误数,请参阅 这篇文章了解更多详情。Windows 不支持此字段。

      ¥majorPageFault <integer> maps to ru_majflt which is the number of major page faults for the process, see this article for more details. This field is not supported on Windows.

    • swappedOut <integer> 映射到 ru_nswap 但不受任何平台支持。

      ¥swappedOut <integer> maps to ru_nswap but is not supported by any platform.

    • fsRead <integer> 映射到 ru_inblock,这是文件系统必须执行输入的次数。

      ¥fsRead <integer> maps to ru_inblock which is the number of times the file system had to perform input.

    • fsWrite <integer> 映射到 ru_oublock,这是文件系统必须执行输出的次数。

      ¥fsWrite <integer> maps to ru_oublock which is the number of times the file system had to perform output.

    • ipcSent <integer> 映射到 ru_msgsnd 但不受任何平台支持。

      ¥ipcSent <integer> maps to ru_msgsnd but is not supported by any platform.

    • ipcReceived <integer> 映射到 ru_msgrcv 但不受任何平台支持。

      ¥ipcReceived <integer> maps to ru_msgrcv but is not supported by any platform.

    • signalsCount <integer> 映射到 ru_nsignals 但不受任何平台支持。

      ¥signalsCount <integer> maps to ru_nsignals but is not supported by any platform.

    • voluntaryContextSwitches <integer> 映射到 ru_nvcsw,这是由于进程在其时间片完成之前(通常是为了等待资源可用)自愿放弃处理器而导致 CPU 上下文切换的次数。Windows 不支持此字段。

      ¥voluntaryContextSwitches <integer> maps to ru_nvcsw which is the number of times a CPU context switch resulted due to a process voluntarily giving up the processor before its time slice was completed (usually to await availability of a resource). This field is not supported on Windows.

    • involuntaryContextSwitches <integer> 映射到 ru_nivcsw,这是由于较高优先级进程变得可运行或因为当前进程超出其时间片而导致 CPU 上下文切换的次数。Windows 不支持此字段。

      ¥involuntaryContextSwitches <integer> maps to ru_nivcsw which is the number of times a CPU context switch resulted due to a higher priority process becoming runnable or because the current process exceeded its time slice. This field is not supported on Windows.

import { resourceUsage } from 'node:process';

console.log(resourceUsage());
/*
  Will output:
  {
    userCPUTime: 82872,
    systemCPUTime: 4143,
    maxRSS: 33164,
    sharedMemorySize: 0,
    unsharedDataSize: 0,
    unsharedStackSize: 0,
    minorPageFault: 2469,
    majorPageFault: 0,
    swappedOut: 0,
    fsRead: 0,
    fsWrite: 8,
    ipcSent: 0,
    ipcReceived: 0,
    signalsCount: 0,
    voluntaryContextSwitches: 79,
    involuntaryContextSwitches: 1
  }
*/const { resourceUsage } = require('node:process');

console.log(resourceUsage());
/*
  Will output:
  {
    userCPUTime: 82872,
    systemCPUTime: 4143,
    maxRSS: 33164,
    sharedMemorySize: 0,
    unsharedDataSize: 0,
    unsharedStackSize: 0,
    minorPageFault: 2469,
    majorPageFault: 0,
    swappedOut: 0,
    fsRead: 0,
    fsWrite: 8,
    ipcSent: 0,
    ipcReceived: 0,
    signalsCount: 0,
    voluntaryContextSwitches: 79,
    involuntaryContextSwitches: 1
  }
*/

process.send(message[, sendHandle[, options]][, callback])#

  • message <Object>

  • sendHandle <net.Server> | <net.Socket>

  • options <Object> 用于参数化某些类型句柄的发送。options 支持以下属性:

    ¥options <Object> used to parameterize the sending of certain types of handles.options supports the following properties:

    • keepOpen <boolean> 当传入 net.Socket 实例时可以使用的值。当为 true 时,套接字在发送过程中保持打开状态。默认值:false

      ¥keepOpen <boolean> A value that can be used when passing instances of net.Socket. When true, the socket is kept open in the sending process. Default: false.

  • callback <Function>

  • 返回:<boolean>

    ¥Returns: <boolean>

如果使用 IPC 通道衍生 Node.js,则可以使用 process.send() 方法向父进程发送消息。消息将作为父对象 ChildProcess 对象上的 'message' 事件接收。

¥If Node.js is spawned with an IPC channel, the process.send() method can be used to send messages to the parent process. Messages will be received as a 'message' event on the parent's ChildProcess object.

如果 Node.js 没有使用 IPC 通道衍生,则 process.send 将是 undefined

¥If Node.js was not spawned with an IPC channel, process.send will be undefined.

消息经过序列化和解析。结果消息可能与最初发送的消息不同。

¥The message goes through serialization and parsing. The resulting message might not be the same as what is originally sent.

process.setegid(id)#

process.setegid() 方法设置进程的有效群组标识。(请参阅 setegid(2)。)id 可以作为数字 ID 或组名称字符串传递。如果指定了群组名,则此方法在解析关联的数字 ID 时会阻塞。

¥The process.setegid() method sets the effective group identity of the process. (See setegid(2).) The id can be passed as either a numeric ID or a group name string. If a group name is specified, this method blocks while resolving the associated a numeric ID.

import process from 'node:process';

if (process.getegid && process.setegid) {
  console.log(`Current gid: ${process.getegid()}`);
  try {
    process.setegid(501);
    console.log(`New gid: ${process.getegid()}`);
  } catch (err) {
    console.error(`Failed to set gid: ${err}`);
  }
}const process = require('node:process');

if (process.getegid && process.setegid) {
  console.log(`Current gid: ${process.getegid()}`);
  try {
    process.setegid(501);
    console.log(`New gid: ${process.getegid()}`);
  } catch (err) {
    console.error(`Failed to set gid: ${err}`);
  }
}

此功能仅适用于 POSIX 平台(即不适用于 Windows 或安卓)。此特性在 Worker 线程中不可用。

¥This function is only available on POSIX platforms (i.e. not Windows or Android). This feature is not available in Worker threads.

process.seteuid(id)#

process.seteuid() 方法设置进程的有效用户身份。(请参阅 seteuid(2)。)id 可以作为数字 ID 或用户名字符串传递。如果指定了用户名,则该方法在解析关联的数字 ID 时会阻塞。

¥The process.seteuid() method sets the effective user identity of the process. (See seteuid(2).) The id can be passed as either a numeric ID or a username string. If a username is specified, the method blocks while resolving the associated numeric ID.

import process from 'node:process';

if (process.geteuid && process.seteuid) {
  console.log(`Current uid: ${process.geteuid()}`);
  try {
    process.seteuid(501);
    console.log(`New uid: ${process.geteuid()}`);
  } catch (err) {
    console.error(`Failed to set uid: ${err}`);
  }
}const process = require('node:process');

if (process.geteuid && process.seteuid) {
  console.log(`Current uid: ${process.geteuid()}`);
  try {
    process.seteuid(501);
    console.log(`New uid: ${process.geteuid()}`);
  } catch (err) {
    console.error(`Failed to set uid: ${err}`);
  }
}

此功能仅适用于 POSIX 平台(即不适用于 Windows 或安卓)。此特性在 Worker 线程中不可用。

¥This function is only available on POSIX platforms (i.e. not Windows or Android). This feature is not available in Worker threads.

process.setgid(id)#

process.setgid() 方法设置进程的群组标识。(请参阅 setgid(2)。)id 可以作为数字 ID 或组名称字符串传递。如果指定了群组名,则此方法在解析关联的数字 ID 时会阻塞。

¥The process.setgid() method sets the group identity of the process. (See setgid(2).) The id can be passed as either a numeric ID or a group name string. If a group name is specified, this method blocks while resolving the associated numeric ID.

import process from 'node:process';

if (process.getgid && process.setgid) {
  console.log(`Current gid: ${process.getgid()}`);
  try {
    process.setgid(501);
    console.log(`New gid: ${process.getgid()}`);
  } catch (err) {
    console.error(`Failed to set gid: ${err}`);
  }
}const process = require('node:process');

if (process.getgid && process.setgid) {
  console.log(`Current gid: ${process.getgid()}`);
  try {
    process.setgid(501);
    console.log(`New gid: ${process.getgid()}`);
  } catch (err) {
    console.error(`Failed to set gid: ${err}`);
  }
}

此功能仅适用于 POSIX 平台(即不适用于 Windows 或安卓)。此特性在 Worker 线程中不可用。

¥This function is only available on POSIX platforms (i.e. not Windows or Android). This feature is not available in Worker threads.

process.setgroups(groups)#

process.setgroups() 方法为 Node.js 进程设置补充群组 ID。这是一个特权操作,需要 Node.js 进程具有 rootCAP_SETGID 能力。

¥The process.setgroups() method sets the supplementary group IDs for the Node.js process. This is a privileged operation that requires the Node.js process to have root or the CAP_SETGID capability.

groups 数组可以包含数字群组 ID、群组名称或两者。

¥The groups array can contain numeric group IDs, group names, or both.

import process from 'node:process';

if (process.getgroups && process.setgroups) {
  try {
    process.setgroups([501]);
    console.log(process.getgroups()); // new groups
  } catch (err) {
    console.error(`Failed to set groups: ${err}`);
  }
}const process = require('node:process');

if (process.getgroups && process.setgroups) {
  try {
    process.setgroups([501]);
    console.log(process.getgroups()); // new groups
  } catch (err) {
    console.error(`Failed to set groups: ${err}`);
  }
}

此功能仅适用于 POSIX 平台(即不适用于 Windows 或安卓)。此特性在 Worker 线程中不可用。

¥This function is only available on POSIX platforms (i.e. not Windows or Android). This feature is not available in Worker threads.

process.setuid(id)#

process.setuid(id) 方法设置进程的用户身份。(请参阅 setuid(2)。)id 可以作为数字 ID 或用户名字符串传递。如果指定了用户名,则该方法在解析关联的数字 ID 时会阻塞。

¥The process.setuid(id) method sets the user identity of the process. (See setuid(2).) The id can be passed as either a numeric ID or a username string. If a username is specified, the method blocks while resolving the associated numeric ID.

import process from 'node:process';

if (process.getuid && process.setuid) {
  console.log(`Current uid: ${process.getuid()}`);
  try {
    process.setuid(501);
    console.log(`New uid: ${process.getuid()}`);
  } catch (err) {
    console.error(`Failed to set uid: ${err}`);
  }
}const process = require('node:process');

if (process.getuid && process.setuid) {
  console.log(`Current uid: ${process.getuid()}`);
  try {
    process.setuid(501);
    console.log(`New uid: ${process.getuid()}`);
  } catch (err) {
    console.error(`Failed to set uid: ${err}`);
  }
}

此功能仅适用于 POSIX 平台(即不适用于 Windows 或安卓)。此特性在 Worker 线程中不可用。

¥This function is only available on POSIX platforms (i.e. not Windows or Android). This feature is not available in Worker threads.

process.setSourceMapsEnabled(val)#

稳定性: 1 - 实验性的

¥Stability: 1 - Experimental

此函数启用或禁用 源映射 v3 对堆栈跟踪的支持。

¥This function enables or disables the Source Map v3 support for stack traces.

它提供与使用命令行选项 --enable-source-maps 启动 Node.js 进程相同的功能。

¥It provides same features as launching Node.js process with commandline options --enable-source-maps.

只有在启用源映射后加载的 JavaScript 文件中的源映射才会被解析和加载。

¥Only source maps in JavaScript files that are loaded after source maps has been enabled will be parsed and loaded.

process.setUncaughtExceptionCaptureCallback(fn)#

process.setUncaughtExceptionCaptureCallback() 函数设置一个函数,当发生未捕获的异常时将调用该函数,该函数将接收异常值本身作为其第一个参数。

¥The process.setUncaughtExceptionCaptureCallback() function sets a function that will be invoked when an uncaught exception occurs, which will receive the exception value itself as its first argument.

如果设置了这样的函数,则不会触发 'uncaughtException' 事件。如果 --abort-on-uncaught-exception 是从命令行传入的或通过 v8.setFlagsFromString() 设置的,则进程不会中止。配置为对异常执行的操作(例如报告生成)也将受到影响

¥If such a function is set, the 'uncaughtException' event will not be emitted. If --abort-on-uncaught-exception was passed from the command line or set through v8.setFlagsFromString(), the process will not abort. Actions configured to take place on exceptions such as report generations will be affected too

要取消捕获功能,可以使用 process.setUncaughtExceptionCaptureCallback(null)。在设置另一个捕获函数时使用非 null 参数调用此方法将引发错误。

¥To unset the capture function, process.setUncaughtExceptionCaptureCallback(null) may be used. Calling this method with a non-null argument while another capture function is set will throw an error.

使用此函数与使用已弃用的 domain 内置模块是相互排斥的。

¥Using this function is mutually exclusive with using the deprecated domain built-in module.

process.sourceMapsEnabled#

稳定性: 1 - 实验性的

¥Stability: 1 - Experimental

process.sourceMapsEnabled 属性返回是否启用了对堆栈跟踪的 源映射 v3 支持。

¥The process.sourceMapsEnabled property returns whether the Source Map v3 support for stack traces is enabled.

process.stderr#

process.stderr 属性返回连接到 stderr (文件描述符 2) 的流。它是一个 net.Socket(它是一个 双工 流)除非 fd 2 引用一个文件,在这种情况下它是一个 可写 流。

¥The process.stderr property returns a stream connected to stderr (fd 2). It is a net.Socket (which is a Duplex stream) unless fd 2 refers to a file, in which case it is a Writable stream.

process.stderr 在一些重要的方面不同于其他 Node.js 流。有关详细信息,请参阅 关于进程 I/O 的注意事项

¥process.stderr differs from other Node.js streams in important ways. See note on process I/O for more information.

process.stderr.fd#

该属性指的是 process.stderr 的底层文件描述符的值。该值固定为 2。在 Worker 线程中,该字段不存在。

¥This property refers to the value of underlying file descriptor of process.stderr. The value is fixed at 2. In Worker threads, this field does not exist.

process.stdin#

process.stdin 属性返回连接到 stdin (文件描述符 0) 的流。它是一个 net.Socket(它是一个 双工 流)除非 fd 0 引用一个文件,在这种情况下它是一个 可读 流。

¥The process.stdin property returns a stream connected to stdin (fd 0). It is a net.Socket (which is a Duplex stream) unless fd 0 refers to a file, in which case it is a Readable stream.

有关如何从 stdin 读取的详细信息,请参阅 readable.read()

¥For details of how to read from stdin see readable.read().

作为 双工 流,process.stdin 也可以在 "old" 模式下使用,与 v0.10 之前为 Node.js 编写的脚本兼容。有关详细信息,请参阅 流兼容性

¥As a Duplex stream, process.stdin can also be used in "old" mode that is compatible with scripts written for Node.js prior to v0.10. For more information see Stream compatibility.

在 "old" 流模式下,stdin 流默认暂停,因此必须调用 process.stdin.resume() 才能从中读取。另请注意,调用 process.stdin.resume() 本身会将流切换到 "old" 模式。

¥In "old" streams mode the stdin stream is paused by default, so one must call process.stdin.resume() to read from it. Note also that calling process.stdin.resume() itself would switch stream to "old" mode.

process.stdin.fd#

该属性指的是 process.stdin 的底层文件描述符的值。该值固定为 0。在 Worker 线程中,该字段不存在。

¥This property refers to the value of underlying file descriptor of process.stdin. The value is fixed at 0. In Worker threads, this field does not exist.

process.stdout#

process.stdout 属性返回连接到 stdout (文件描述符 1) 的流。它是一个 net.Socket(它是一个 双工 流)除非 fd 1 引用一个文件,在这种情况下它是一个 可写 流。

¥The process.stdout property returns a stream connected to stdout (fd 1). It is a net.Socket (which is a Duplex stream) unless fd 1 refers to a file, in which case it is a Writable stream.

例如,要将 process.stdin 复制到 process.stdout

¥For example, to copy process.stdin to process.stdout:

import { stdin, stdout } from 'node:process';

stdin.pipe(stdout);const { stdin, stdout } = require('node:process');

stdin.pipe(stdout);

process.stdout 在一些重要的方面不同于其他 Node.js 流。有关详细信息,请参阅 关于进程 I/O 的注意事项

¥process.stdout differs from other Node.js streams in important ways. See note on process I/O for more information.

process.stdout.fd#

该属性指的是 process.stdout 的底层文件描述符的值。该值固定为 1。在 Worker 线程中,该字段不存在。

¥This property refers to the value of underlying file descriptor of process.stdout. The value is fixed at 1. In Worker threads, this field does not exist.

关于进程 I/O 的注意事项#

¥A note on process I/O

process.stdoutprocess.stderr 在重要方面与其他 Node.js 流不同:

¥process.stdout and process.stderr differ from other Node.js streams in important ways:

  1. 它们分别由 console.log()console.error() 内部使用。

    ¥They are used internally by console.log() and console.error(), respectively.

  2. 写入可能是同步的,具体取决于流连接到什么以及系统是 Windows 还是 POSIX:

    ¥Writes may be synchronous depending on what the stream is connected to and whether the system is Windows or POSIX:

    • 档案:在 Windows 和 POSIX 上同步

      ¥Files: synchronous on Windows and POSIX

    • TTY(终端):在 Windows 上异步,在 POSIX 上同步

      ¥TTYs (Terminals): asynchronous on Windows, synchronous on POSIX

    • 管道(和套接字):在 Windows 上同步,在 POSIX 上异步

      ¥Pipes (and sockets): synchronous on Windows, asynchronous on POSIX

这些行为部分是出于历史原因,因为更改它们会导致向后不兼容,但某些用户也期望它们。

¥These behaviors are partly for historical reasons, as changing them would create backward incompatibility, but they are also expected by some users.

同步写入避免了诸如使用 console.log()console.error() 写入的输出意外交错的问题,或者如果在异步写入完成之前调用 process.exit() 则根本不写入。有关详细信息,请参阅 process.exit()

¥Synchronous writes avoid problems such as output written with console.log() or console.error() being unexpectedly interleaved, or not written at all if process.exit() is called before an asynchronous write completes. See process.exit() for more information.

警告:同步写入会阻塞事件循环,直到写入完成。在输出到文件的情况下,这可能几乎是瞬时的,但在系统负载高、接收端未读取管道或终端或文件系统速度较慢的情况下,事件循环可能经常被阻塞足够长,足以对性能产生严重的负面影响。这在写入交互式终端会话时可能不是问题,但在对流程输出流进行生产日志记录时要特别小心。

¥Warning: Synchronous writes block the event loop until the write has completed. This can be near instantaneous in the case of output to a file, but under high system load, pipes that are not being read at the receiving end, or with slow terminals or file systems, it's possible for the event loop to be blocked often enough and long enough to have severe negative performance impacts. This may not be a problem when writing to an interactive terminal session, but consider this particularly careful when doing production logging to the process output streams.

要检查流是否连接到 TTY 上下文,请检查 isTTY 属性。

¥To check if a stream is connected to a TTY context, check the isTTY property.

例如:

¥For instance:

$ node -p "Boolean(process.stdin.isTTY)"
true
$ echo "foo" | node -p "Boolean(process.stdin.isTTY)"
false
$ node -p "Boolean(process.stdout.isTTY)"
true
$ node -p "Boolean(process.stdout.isTTY)" | cat
false 

有关更多信息,请参阅 TTY 文档。

¥See the TTY documentation for more information.

process.throwDeprecation#

process.throwDeprecation 的初始值表示当前 Node.js 进程是否设置了 --throw-deprecation 标志。process.throwDeprecation 是可变的,因此可能会在运行时更改弃用警告是否导致错误。有关详细信息,请参阅 'warning' 事件emitWarning() 方法 的文档。

¥The initial value of process.throwDeprecation indicates whether the --throw-deprecation flag is set on the current Node.js process. process.throwDeprecation is mutable, so whether or not deprecation warnings result in errors may be altered at runtime. See the documentation for the 'warning' event and the emitWarning() method for more information.

$ node --throw-deprecation -p "process.throwDeprecation"
true
$ node -p "process.throwDeprecation"
undefined
$ node
> process.emitWarning('test', 'DeprecationWarning');
undefined
> (node:26598) DeprecationWarning: test
> process.throwDeprecation = true;
true
> process.emitWarning('test', 'DeprecationWarning');
Thrown:
[DeprecationWarning: test] { name: 'DeprecationWarning' } 

process.title#

process.title 属性返回当前进程标头(即返回 ps 的当前值)。为 process.title 分配一个新值会修改 ps 的当前值。

¥The process.title property returns the current process title (i.e. returns the current value of ps). Assigning a new value to process.title modifies the current value of ps.

分配新值时,不同平台会对标头施加不同的最大长度限制。通常这种限制是相当有限的。例如,在 Linux 和 macOS 上,process.title 被限制为二进制名称的大小加上命令行参数的长度,因为设置 process.title 会覆盖进程的 argv 内存。Node.js v0.8 通过覆盖 environ 内存允许更长的进程标头字符串,但这在某些(相当模糊的)情况下可能不安全和混乱。

¥When a new value is assigned, different platforms will impose different maximum length restrictions on the title. Usually such restrictions are quite limited. For instance, on Linux and macOS, process.title is limited to the size of the binary name plus the length of the command-line arguments because setting the process.title overwrites the argv memory of the process. Node.js v0.8 allowed for longer process title strings by also overwriting the environ memory but that was potentially insecure and confusing in some (rather obscure) cases.

将值分配给 process.title 可能不会在进程管理器应用(例如 macOS 活动监视器或 Windows 服务管理器)中产生准确的标签。

¥Assigning a value to process.title might not result in an accurate label within process manager applications such as macOS Activity Monitor or Windows Services Manager.

process.traceDeprecation#

process.traceDeprecation 属性指示是否在当前 Node.js 进程上设置了 --trace-deprecation 标志。有关此标志行为的更多信息,请参阅 'warning' 事件emitWarning() 方法 的文档。

¥The process.traceDeprecation property indicates whether the --trace-deprecation flag is set on the current Node.js process. See the documentation for the 'warning' event and the emitWarning() method for more information about this flag's behavior.

process.umask()#

稳定性: 0 - 已弃用。不带参数调用 process.umask() 会导致进程范围的 umask 被写入两次。这在线程之间引入了竞争条件,并且是一个潜在的安全漏洞。没有安全的、跨平台的替代 API。

¥Stability: 0 - Deprecated. Calling process.umask() with no argument causes the process-wide umask to be written twice. This introduces a race condition between threads, and is a potential security vulnerability. There is no safe, cross-platform alternative API.

process.umask() 返回 Node.js 进程的文件模式创建掩码。子进程从父进程继承掩码。

¥process.umask() returns the Node.js process's file mode creation mask. Child processes inherit the mask from the parent process.

process.umask(mask)#

process.umask(mask) 设置 Node.js 进程的文件模式创建掩码。子进程从父进程继承掩码。返回上一个掩码。

¥process.umask(mask) sets the Node.js process's file mode creation mask. Child processes inherit the mask from the parent process. Returns the previous mask.

import { umask } from 'node:process';

const newmask = 0o022;
const oldmask = umask(newmask);
console.log(
  `Changed umask from ${oldmask.toString(8)} to ${newmask.toString(8)}`,
);const { umask } = require('node:process');

const newmask = 0o022;
const oldmask = umask(newmask);
console.log(
  `Changed umask from ${oldmask.toString(8)} to ${newmask.toString(8)}`,
);

Worker 线程中,process.umask(mask) 会抛出异常。

¥In Worker threads, process.umask(mask) will throw an exception.

process.uptime()#

process.uptime() 方法返回当前 Node.js 进程已经运行的秒数。

¥The process.uptime() method returns the number of seconds the current Node.js process has been running.

返回值包括几分之一秒。使用 Math.floor() 获得整秒。

¥The return value includes fractions of a second. Use Math.floor() to get whole seconds.

process.version#

process.version 属性包含 Node.js 版本字符串。

¥The process.version property contains the Node.js version string.

import { version } from 'node:process';

console.log(`Version: ${version}`);
// Version: v14.8.0const { version } = require('node:process');

console.log(`Version: ${version}`);
// Version: v14.8.0

要获取不带前缀 v 的版本字符串,请使用 process.versions.node

¥To get the version string without the prepended v, use process.versions.node.

process.versions#

process.versions 属性返回对象,其中列出了 Node.js 的版本字符串及其依赖。process.versions.modules 表示当前的 ABI 版本,每当 C++ API 更改时都会增加。Node.js 将拒绝加载针对不同模块 ABI 版本编译的模块。

¥The process.versions property returns an object listing the version strings of Node.js and its dependencies. process.versions.modules indicates the current ABI version, which is increased whenever a C++ API changes. Node.js will refuse to load modules that were compiled against a different module ABI version.

import { versions } from 'node:process';

console.log(versions);const { versions } = require('node:process');

console.log(versions);

将生成类似于以下内容的对象:

¥Will generate an object similar to:

{ node: '23.0.0',
  acorn: '8.11.3',
  ada: '2.7.8',
  ares: '1.28.1',
  base64: '0.5.2',
  brotli: '1.1.0',
  cjs_module_lexer: '1.2.2',
  cldr: '45.0',
  icu: '75.1',
  llhttp: '9.2.1',
  modules: '127',
  napi: '9',
  nghttp2: '1.61.0',
  nghttp3: '0.7.0',
  ngtcp2: '1.3.0',
  openssl: '3.0.13+quic',
  simdjson: '3.8.0',
  simdutf: '5.2.4',
  sqlite: '3.46.0',
  tz: '2024a',
  undici: '6.13.0',
  unicode: '15.1',
  uv: '1.48.0',
  uvwasi: '0.0.20',
  v8: '12.4.254.14-node.11',
  zlib: '1.3.0.1-motley-7d77fb7' } 

退出代码#

¥Exit codes

当没有更多异步操作挂起时,Node.js 通常会以 0 状态代码退出。在其他情况下使用以下状态代码:

¥Node.js will normally exit with a 0 status code when no more async operations are pending. The following status codes are used in other cases:

  • 1 未捕获的致命异常:有一个未捕获的异常,它没有被域或 'uncaughtException' 事件处理程序处理。

    ¥1 Uncaught Fatal Exception: There was an uncaught exception, and it was not handled by a domain or an 'uncaughtException' event handler.

  • 2:未使用(由 Bash 预留用于内置误用)

    ¥2: Unused (reserved by Bash for builtin misuse)

  • 3 内部 JavaScript 解析错误:Node.js 引导过程中内部的 JavaScript 源代码导致解析错误。这是极其罕见的,通常只能在 Node.js 本身的开发过程中发生。

    ¥3 Internal JavaScript Parse Error: The JavaScript source code internal in the Node.js bootstrapping process caused a parse error. This is extremely rare, and generally can only happen during development of Node.js itself.

  • 4 内部 JavaScript 评估失败:Node.js 引导过程内部的 JavaScript 源代码在评估时未能返回函数值。这是极其罕见的,通常只能在 Node.js 本身的开发过程中发生。

    ¥4 Internal JavaScript Evaluation Failure: The JavaScript source code internal in the Node.js bootstrapping process failed to return a function value when evaluated. This is extremely rare, and generally can only happen during development of Node.js itself.

  • 5 致命错误:V8 中有一个不可恢复的致命错误。通常将打印带有前缀 FATAL ERROR 的消息到标准错误。

    ¥5 Fatal Error: There was a fatal unrecoverable error in V8. Typically a message will be printed to stderr with the prefix FATAL ERROR.

  • 6 非函数内部异常处理程序:有一个未捕获的异常,但内部致命异常处理函数不知何故设置为非函数,无法调用。

    ¥6 Non-function Internal Exception Handler: There was an uncaught exception, but the internal fatal exception handler function was somehow set to a non-function, and could not be called.

  • 7 内部异常处理程序运行时失败:有一个未捕获的异常,内部致命异常处理函数本身在尝试处理它时抛出了一个错误。例如,如果 'uncaughtException'domain.on('error') 句柄抛出错误,就会发生这种情况。

    ¥7 Internal Exception Handler Run-Time Failure: There was an uncaught exception, and the internal fatal exception handler function itself threw an error while attempting to handle it. This can happen, for example, if an 'uncaughtException' or domain.on('error') handler throws an error.

  • 8:未使用。在以前版本的 Node.js 中,退出码 8 有时表示未捕获的异常。

    ¥8: Unused. In previous versions of Node.js, exit code 8 sometimes indicated an uncaught exception.

  • 9 无效的参数:指定了未知选项,或者提供了需要值的选项但未提供值。

    ¥9 Invalid Argument: Either an unknown option was specified, or an option requiring a value was provided without a value.

  • 10 内部 JavaScript 运行时故障:调用引导函数时,Node.js 引导过程内部的 JavaScript 源代码抛出错误。这是极其罕见的,通常只能在 Node.js 本身的开发过程中发生。

    ¥10 Internal JavaScript Run-Time Failure: The JavaScript source code internal in the Node.js bootstrapping process threw an error when the bootstrapping function was called. This is extremely rare, and generally can only happen during development of Node.js itself.

  • 12 无效的调试参数:已设置 --inspect 和/或 --inspect-brk 选项,但选择的端口号无效或不可用。

    ¥12 Invalid Debug Argument: The --inspect and/or --inspect-brk options were set, but the port number chosen was invalid or unavailable.

  • 13 悬而未决的高层等待:await 在顶层代码的函数外部使用,但传递的 Promise 从未解决。

    ¥13 Unsettled Top-Level Await: await was used outside of a function in the top-level code, but the passed Promise never settled.

  • 14 快照失败:Node.js 开始构建 V8 启动快照,但由于未满足应用状态的某些要求而失败。

    ¥14 Snapshot Failure: Node.js was started to build a V8 startup snapshot and it failed because certain requirements of the state of the application were not met.

  • >128 信号退出:如果 Node.js 收到 SIGKILLSIGHUP 等致命信号,则其退出代码将为 128 加上信号代码的值。这是标准的 POSIX 实践,因为退出码被定义为 7 位整数,并且信号退出设置高位,然后包含信号代码的值。例如,信号 SIGABRT 的值是 6,因此预期的退出码将是 128 + 6134

    ¥>128 Signal Exits: If Node.js receives a fatal signal such as SIGKILL or SIGHUP, then its exit code will be 128 plus the value of the signal code. This is a standard POSIX practice, since exit codes are defined to be 7-bit integers, and signal exits set the high-order bit, and then contain the value of the signal code. For example, signal SIGABRT has value 6, so the expected exit code will be 128 + 6, or 134.

Node.js 中文网 - 粤ICP备13048890号