Node.js v18.20.8 文档


进程#>

【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'

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

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

  • 显式调用 process.exit() 方法;
  • Node.js 事件循环不再有其他需要执行的任务。

此时无法阻止事件循环退出,一旦所有 '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 选项设置为 advancedmessage 参数可能包含 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 - 已弃用

  • type <string> 解析类型。可以是 'resolve''reject'
  • promise <Promise> 被解析或拒绝超过一次的 Promise。
  • value <any> 在最初解析之后用于解析或拒绝 Promise 的值。

每当 Promise 出现以下情况时,会触发 'multipleResolves' 事件:

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

  • 多次已解决。
  • 多次被拒。
  • 解决后被拒。
  • 拒绝后已解决。

在使用 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'

'rejectionHandled' 事件会在 Promise 被拒绝后且在其上附加了错误处理器(例如使用 promise.catch())晚于 Node.js 事件循环的一个轮次时触发。

【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).】

事件:'uncaughtException'#>

【Event: 'uncaughtException'

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

当一个未捕获的 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';

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

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

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

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 的替代方法。未处理的异常本质上意味着应用处于未定义状态。尝试在未正确处理异常的情况下恢复应用代码可能会导致额外的、无法预料的问题。

从事件处理程序内部抛出的异常将不会被捕获。相反,进程将以非零退出代码退出,并打印堆栈跟踪。这是为了避免无限递归。

【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> 未捕获的异常。
  • origin <string> 表示异常的来源是未处理的拒绝还是同步错误。可以是 'uncaughtException''unhandledRejection'。当异常发生在基于 Promise 的异步环境中(或者 Promise 被拒绝)且 --unhandled-rejections 标志设置为 strictthrow(默认值)且拒绝未被处理时,或者当在命令行入口点的 ES 模块静态加载阶段发生拒绝时,会使用后者。

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

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

安装 'uncaughtExceptionMonitor' 监听器不会改变 'uncaughtException' 事件触发后的行为。如果没有安装 '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 对象)。
  • promise <Promise> 被拒绝的 promise。

'unhandledRejection' 事件会在每当一个 Promise 被拒绝且在事件循环的一轮内没有为该 Promise 附加错误处理程序时触发。在使用 Promise 编程时,异常被封装为“被拒绝的 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' 事件通常的处理方式一样。为了应对此类失败,可以在 resource.loaded 上附加一个非操作性的 .catch(() => { }) 处理程序,这将阻止 '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> 警告的关键属性包括:
    • name <string> 警告的名称。默认值: 'Warning'
    • message <string> 系统提供的警告描述。
    • stack <string> 发生警告的代码位置的堆栈跟踪。

每当 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 命令行选项来抑制默认的控制台输出,但 process 对象仍会触发 'warning' 事件。

【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.】

下面的示例说明了当向某个事件添加了过多监听器时,会打印到 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'.】

事件:'worker'#>

【Event: 'worker'

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

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

触发自定义警告#>

【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' 属性来标识 弃用代码
  • 'ExperimentalWarning' - 表示使用了实验性的 Node.js API 或功能。这类功能必须谨慎使用,因为它们可能随时发生变化,并且不像受支持的功能那样遵循严格的语义版本控制和长期支持政策。
  • 'MaxListenersExceededWarning' - 表示在 EventEmitterEventTarget 上为某个事件注册的监听器过多。这通常是内存泄漏的一个迹象。
  • 'TimeoutOverflowWarning' - 表示向 setTimeout()setInterval() 函数提供了一个无法容纳在 32 位有符号整数中的数值。
  • 'UnsupportedWarning' - 表示使用了不受支持的选项或功能,该选项或功能将被忽略,而不会被视为错误。一个例子是在使用 HTTP/2 兼容 API 时使用 HTTP 响应状态消息。

信号事件#>

【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 保留用于启动 调试器。可以安装一个监听器,但这样做可能会干扰调试器。
  • 'SIGTERM''SIGINT' 在非 Windows 平台上有默认的处理程序,会在以代码 128 + 信号编号 退出之前重置终端模式。如果为其中一个信号安装了监听器,其默认行为将被移除(Node.js 将不再退出)。
  • 默认情况下会忽略 'SIGPIPE'。可以为其安装一个监听器。
  • 在 Windows 上,当控制台窗口关闭时会生成 'SIGHUP',在其他平台上则在各种类似情况下生成。请参阅 signal(7)。它可以安装监听器,但 Node.js 会在大约 10 秒后被 Windows 无条件终止。在非 Windows 平台上,SIGHUP 的默认行为是终止 Node.js,但一旦安装了监听器,其默认行为将被移除。
  • Windows 不支持 'SIGTERM',但可以监听它。
  • 从终端发送的 'SIGINT' 在所有平台上都受支持,通常可以通过 Ctrl+C 生成(虽然这可能是可配置的)。 当启用 终端原始模式 并使用 Ctrl+C 时,它不会被生成。
  • 'SIGBREAK' 会在 Windows 上在按下 Ctrl+Break 时触发。在非 Windows 平台上,可以监听它,但没有方法发送或生成它。
  • 'SIGWINCH' 会在控制台大小发生变化时发送。在 Windows 上,这只会在控制台写入时发生,当光标被移动,或在使用原始模式的可读 tty 时发生。
  • 'SIGKILL' 无法安装监听器,它将在所有平台上无条件终止 Node.js。
  • 'SIGSTOP' 不能安装监听器。
  • 'SIGBUS''SIGFPE''SIGSEGV''SIGILL',当不是通过 kill(2) 人为触发时,本质上会使进程处于不安全状态,此时调用 JS 监听器是不安全的。这样做可能会导致进程停止响应。
  • 0 可以用来测试进程是否存在,如果进程存在则没有任何效果,如果进程不存在则会抛出错误。

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():】

  • 发送 SIGINTSIGTERMSIGKILL 会导致目标进程被无条件终止,之后,子进程将报告该进程是被信号终止的。
  • 发送信号 0 可以作为一种跨平台的方法来测试进程是否存在。

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 属性是一个特殊的、只读的 Set,包含 NODE_OPTIONS 环境变量中允许的标志。

【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

  • 标志可以省略前导的单个(-)或双(--)破折号;例如, inspect-brk 表示 --inspect-brk,或 r 表示 -r
  • 传递给 V8 的标志(如 --v8-options 中列出)可以将一个或多个非前导破折号替换为下划线,反之亦然; 例如,--perf_basic_prof--perf-basic-prof--perf_basic-prof 等。
  • 标志可以包含一个或多个等号(=);第一次出现的等号及其之后的所有字符将被忽略; 例如,--stack-trace-limit=100
  • 标志必须NODE_OPTIONS 中允许使用。

在迭代 process.allowedNodeEnvironmentFlags 时,标志只会出现一次;每个标志都以一个或多个短横线开头。传递给 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.allowedNodeEnvironmentFlagsadd()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''mips''mipsel''ppc''ppc64''s390''s390x''x64'

【The operating system CPU architecture for which the Node.js binary was compiled. Possible values are: 'arm', 'arm64', 'ia32', 'mips','mipsel', 'ppc', 'ppc64', '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 an 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_dtrace: 'false',
     node_use_openssl: 'true',
     node_shared_openssl: 'false',
     strict_aliasing: 'true',
     target_arch: 'x64',
     v8_use_snapshot: 1
   }
} 

process.config 属性不是只读的,并且在生态系统中存在已知的模块会扩展、修改或完全替换 process.config 的值。

【The process.config property is not read-only and there are existing modules in the ecosystem that are known to extend, modify, or entirely replace the value of process.config.】

修改 process.config 属性或 process.config 对象的任何子属性已被弃用。process.config 将在未来的版本中变为只读。

【Modifying the process.config property, or any child-property of the process.config object has been deprecated. The process.config will be made read-only in a future release.】

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,就无法再通过 IPC 通道使用 process.send() 发送消息。

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

process.constrainedMemory()#>

稳定性: 1 - 实验性

获取进程可用的内存量(以字节为单位),基于操作系统施加的限制。如果没有此类限制,或者限制未知,则返回 undefined

【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, undefined is returned.】

有关更多信息,请参阅 uv_get_constrained_memory

【See uv_get_constrained_memory for more information.】

process.cpuUsage([previousValue])#>

process.cpuUsage() 方法返回当前进程的用户和系统 CPU 使用时间,以包含 usersystem 属性的对象形式表示,其值为微秒(百万分之一秒)。这些值分别衡量在用户代码和系统代码中花费的时间,如果多个 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++ 插件,并且除非在特殊情况下,一般不应该直接使用。换句话说,除非有特定原因(例如自定义 dlopen 标志或从 ES 模块加载),否则应优先使用 require(),而不是 process.dlopen()

【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 实例。C++ 插件导出的函数随后可以通过 module.exports 访问。

【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> 要发出的警告。
  • options <Object>
    • type <string>warning 是一个 String 时,type 是用于指定要发出的警告类型的名称。默认值: 'Warning'
    • code <string> 要发出的警告实例的唯一标识符。
    • ctor <Function>warning 是一个 String 时,ctor 是一个可选函数,用于限制生成的堆栈跟踪。默认值: process.emitWarning
    • detail <string> 错误中要包含的附加文本。

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> 要发出的警告。
  • type <string>warning 是一个 String 时,type 是用于发出警告类型的名称。默认值: 'Warning'
  • code <string> 发出的警告实例的唯一标识符。
  • ctor <Function>warning 是一个 String 时,ctor 是一个可选函数,用于限制生成的堆栈跟踪。默认值: 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!

在前面的每个示例中,process.emitWarning() 会在内部生成一个 Error 对象,并将其传递给 '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.】

如果警告类型为 'DeprecationWarning',将实现以下额外处理:

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

  • 如果使用 --throw-deprecation 命令行标志,弃用警告将作为异常抛出,而不是作为事件发出。
  • 如果使用 --no-deprecation 命令行标志,弃用警告将被抑制。
  • 如果使用 --trace-deprecation 命令行标志,弃用警告将打印到 stderr,并附带完整的堆栈跟踪。

避免重复警告#>

【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 属性返回一个包含用户环境的对象。参考 environ(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 --harmony script.js --version 

process.execArgv 中的结果:

【Results in process.execArgv:】

['--harmony'] 

还有 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])#>

  • code <integer> 退出代码。默认值: 0

process.exit() 方法指示 Node.js 以同步方式终止进程,并使用 code 作为退出状态。如果省略 code,退出将使用“成功”代码 0,或者如果已设置过 process.exitCode,则使用其值。Node.js 在所有 'exit' 事件监听器被调用之前不会终止。

【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.】

要以“失败”代码退出:

【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.getActiveResourcesInfo()#>

稳定性: 1 - 实验性

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.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 或 Android)。

【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 或 Android)。

【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 或 Android)。

【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 或 Android)。

【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 或 Android)。

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

  • time 整数数组[] 之前调用 process.hrtime() 的结果
  • 返回: 整数数组[]

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

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

process.hrtime() 方法返回当前的高分辨率实时时间,以 [秒, 纳秒] 元组数组的形式,其中 纳秒 是无法用秒精度表示的实时时间的剩余部分。

【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() 的结果,用于与当前时间做差异计算。如果传入的参数不是一个元组 Array,将抛出 TypeError。传入用户自定义的数组而不是之前 process.hrtime() 调用的结果可能会导致未定义行为。

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

【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 或 Android)。 此功能在 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> 进程 ID
  • signal <string> | <number> 要发送的信号,可以是字符串或数字。 默认值: 'SIGTERM'

process.kill() 方法会向由 pid 指定的进程发送 signal

【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 来测试进程是否存在。如果在 Windows 平台上使用 pid 来终止进程组,将会抛出错误。

【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.mainModule#>

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

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 的内存使用情况。
  • external 指与 V8 管理的 JavaScript 对象绑定的 C++ 对象的内存使用。
  • rss(常驻集大小)是进程在主内存设备中占用的空间(这是总分配内存的一个子集),包括所有 C++ 和 JavaScript 对象及代码。
  • arrayBuffers 指为 ArrayBufferSharedArrayBuffer 分配的内存,包括所有 Node.js Buffers。这也包含在 external 值中。当 Node.js 作为嵌入式库使用时,此值可能为 0,因为在这种情况下可能无法跟踪 ArrayBuffer 的分配。

在使用 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])#>

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

process.nextTick() 会将 callback 添加到“下一次执行队列”。这个队列会在当前 JavaScript 栈上的操作完成后、事件循环继续之前被完全清空。如果递归调用 process.nextTick(),可能会创建一个无限循环。有关更多背景信息,请参见 事件循环 指南。

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.

对于 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() 的一种替代方案,它同样使用微任务队列来延迟函数的执行,该队列用于执行已解决 Promise 的 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.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 对 Android 的支持 是实验性的

【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,其中包含与当前版本相关的元数据,包括源代码压缩包和仅包含头文件的压缩包的 URL。

【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 包含以下属性:

  • name <string> 一个始终为 'node' 的值。
  • sourceUrl <string> 是指向包含当前版本源代码的 .tar.gz 文件的绝对 URL。
  • headersUrl<string> 是指向包含当前版本源头文件的 .tar.gz 文件的绝对 URL。该文件比完整的源代码文件小得多,可用于编译 Node.js 原生插件。
  • libUrl <string> | <undefined> 是指向与当前版本和架构匹配的 node.lib 文件的绝对 URL。该文件用于编译 Node.js 本地插件。此属性仅存在于 Windows 版的 Node.js,在其他平台上将不存在.
  • lts <string> | <undefined> 是一个字符串标签,用于标识此版本的 长期支持 标签。此属性仅存在于 LTS 版本中,对于所有其他版本类型(包括 Current 版本)则为 undefined。有效值包括 LTS 版本代号(包括已不再受支持的代号)。
    • “Fermium”,用于14.x LTS系列,起始于14.15.0。
    • 16.x LTS系列从16.13.0开始称为“Gallium”。
    • 'Hydrogen' 指的是从 18.12.0 开始的 18.x LTS 版本系列。 有关其他 LTS 版本的代号,请参见 Node.js 更新日志存档
{
  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.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#>

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

【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',报告将分别写入进程的标准输出或标准错误。

【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 堆栈的自定义错误。
  • 返回值: <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 进程的当前工作目录。

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

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

将诊断报告写入文件。如果未提供 filename,默认文件名将包含日期、时间、进程ID(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',报告将分别写入进程的标准输出或标准错误。

【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_getrusage 调用,该调用返回一个 uv_rusage_t 结构体
    • userCPUTime <integer> 映射到以微秒计算的 ru_utime。它与 process.cpuUsage().user 的值相同。
    • systemCPUTime <integer> 映射到以微秒计算的 ru_stime。它与 process.cpuUsage().system 的值相同。
    • maxRSS <integer> 映射到 ru_maxrss,表示使用的最大常驻内存集大小,单位为千字节。
    • sharedMemorySize <integer> 映射到 ru_ixrss,但不被任何平台支持。
    • unsharedDataSize <integer> 映射到 ru_idrss,但不受任何平台支持。
    • unsharedStackSize <integer> 映射到 ru_isrss,但不受任何平台支持。
    • minorPageFault <integer> 映射到 ru_minflt,表示该进程的次要页面错误次数,详见 本文提供更多详细信息
    • majorPageFault <integer> 对应于 ru_majflt,表示该进程的主要缺页错误数,参见 本文提供更多详细信息。此字段在 Windows 上不受支持。
    • swappedOut <integer> 映射到 ru_nswap,但不被任何平台支持。
    • 'fsRead' <integer> 映射到 'ru_inblock',即 文件系统必须执行输入。
    • fsWrite <integer> 映射到 ru_oublock,它表示文件系统必须执行输出的次数。
    • ipcSent <integer> 映射到 ru_msgsnd,但不被任何平台支持。
    • 'ipcReceived' <integer> 映射到 'ru_msgrcv',但不被任何 平台。
    • signalsCount <integer> 映射到 ru_nsignals,但不被任何平台支持。
    • voluntaryContextSwitches <integer> 对应于 ru_nvcsw,表示 CPU 上下文切换发生的次数,这种切换是由于进程在其时间片未完成之前自愿放弃处理器(通常是为了等待某个资源的可用性)。此字段在 Windows 上不受支持。
    • involuntaryContextSwitches <integer> 映射到 ru_nivcsw,表示由于高优先级进程变为可运行状态或当前进程超出其时间片而导致的 CPU 上下文切换次数。此字段在 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])#>

如果 Node.js 是通过 IPC 通道创建的,可以使用 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 或 Android)。 此功能在 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 或 Android)。 此功能在 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 或 Android)。 此功能在 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)#>

  • groups 整数数组[]

process.setgroups() 方法用于设置 Node.js 进程的补充组 ID。这是一个需要特权的操作,要求 Node.js 进程具有 root 权限或 CAP_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 或 Android)。 此功能在 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 或 Android)。 此功能在 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 - 实验性

此功能用于启用或禁用对堆栈跟踪的 源映射 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 - 实验性

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(这是一种 双工 流),除非文件描述符 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.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(这是一种 双工 流),除非文件描述符 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 也可以以“旧”模式使用,该模式兼容为 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.】

在“旧”流模式下,stdin 流默认是暂停的,因此必须调用 process.stdin.resume() 才能读取它。注意,调用 process.stdin.resume() 本身也会将流切换到“旧”模式。

【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(这是一种 双工 流),除非文件描述符 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.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 流不同:

  1. 它们分别由 console.log()console.error() 内部使用。

  2. 写入操作可能是同步的,这取决于流所连接的对象以及系统是 Windows 还是 POSIX:

    • 文件:在 Windows 和 POSIX 上为 同步

    • TTY(终端):在 Windows 上为 异步,在 POSIX 上为 同步

    • 管道(和套接字):在 Windows 上为 同步,在 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.】

要检查一个流是否连接到 文字电话 上下文,请检查 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 

有关更多信息,请参阅 文字电话 文档。

【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。

process.umask() 返回 Node.js 进程的文件模式创建掩码。子进程会继承父进程的掩码。

process.umask(mask)#>

process.umask(mask) 设置 Node.js 进程的文件模式创建掩码。子进程会继承父进程的掩码。返回先前的掩码。

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: '11.13.0',
  v8: '7.0.276.38-node.18',
  uv: '1.27.0',
  zlib: '1.2.11',
  brotli: '1.0.7',
  ares: '1.15.0',
  modules: '67',
  nghttp2: '1.34.0',
  napi: '4',
  llhttp: '1.1.1',
  openssl: '1.1.1b',
  cldr: '34.0',
  icu: '63.1',
  tz: '2018e',
  unicode: '11.0' } 

退出代码#>

【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' 事件处理程序处理。
  • 2:未使用(Bash 保留用于内置命令误用)
  • 3 内部 JavaScript 解析错误:Node.js 引导过程中内部的 JavaScript 源代码导致了解析错误。这种情况极为罕见,通常只会在 Node.js 自身开发过程中发生。
  • 4 内部 JavaScript 评估失败:Node.js 启动过程中的内部 JavaScript 源代码在执行时未能返回函数值。这种情况极为罕见,通常仅在 Node.js 本身开发过程中才可能发生。
  • 5 致命错误:V8 中发生了无法恢复的致命错误。通常会在标准错误输出中打印一条以 FATAL ERROR 为前缀的消息。
  • 6 非函数内部异常处理器:出现了未捕获的异常,但内部致命异常处理器函数被意外设置为非函数,无法调用。
  • 7 内部异常处理程序运行时故障:出现了未捕获的异常,并且内部致命异常处理函数在尝试处理该异常时自身抛出了错误。例如,如果 'uncaughtException'domain.on('error') 处理程序抛出错误,就可能发生这种情况。
  • “8”:未使用。在之前的版本中,Node.js有时会使用出口代码8 表示未接获的例外。
  • 9 无效参数:要么指定了未知选项,要么需要值的选项未提供值。
  • 10 内部 JavaScript 运行时失败:在调用引导函数时,Node.js 引导过程中内部的 JavaScript 源代码抛出了错误。这种情况极其罕见,通常只会在 Node.js 本身的开发过程中发生。
  • 12 无效的调试参数:已设置 --inspect 和/或 --inspect-brk 选项,但所选择的端口号无效或不可用。
  • 13 未完成的顶层 await:在顶层代码中使用了 await,但传入的 Promise 从未解决。
  • 14 快照失败:Node.js 启动时试图构建 V8 启动快照,但由于未满足应用状态的某些要求而失败。
  • >128 信号退出:如果 Node.js 收到致命信号,例如 SIGKILLSIGHUP,那么它的退出码将是 128 加上信号代码的值。这是标准的 POSIX 做法,因为退出码被定义为 7 位整数,信号退出会设置高位,然后包含信号代码的值。例如,信号 SIGABRT 的值为 6,因此预计的退出码将是 128 + 6,即 134
Node.js 中文网 - 粤ICP备13048890号