Node.js v12.6.0 文档




The process object is a global that provides information about, and control over, the current Node.js process. As a global, it is always available to Node.js applications without using require(). It can also be explicitly accessed using require():

const process = require('process');



process 对象是 EventEmitter 的实例。

'beforeExit' 事件#


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

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

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

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

'disconnect' 事件#


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

'exit' 事件#


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

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

此时无法阻止退出事件循环,并且一旦所有 'exit' 事件的监听器都已完成运行时,Node.js 进程将终止。

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

process.on('exit', (code) => {
  console.log(`退出码: ${code}`);

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

process.on('exit', (code) => {
  setTimeout(() => {
  }, 0);

'message' 事件#


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

消息会进行序列化和解析。 生成的消息可能与最初发送的消息不同。

'multipleResolves' 事件#


  • type <string> The resolution type. One of 'resolve' or 'reject'.
  • promise <Promise> The promise that resolved or rejected more than once.
  • value <any> The value with which the promise was either resolved or rejected after the original resolve.

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

  • Resolved more than once.
  • Rejected more than once.
  • Rejected after resolve.
  • Resolved after reject.

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.

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

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

'rejectionHandled' 事件#


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

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

Promise 对象之前已经在 'unhandledRejection' 事件中触发,但在处理过程中获得了拒绝处理函数。

Promise 链中没有顶层的概念,总是可以处理拒绝。 本质上自身是异步的,可以在未来的某个时间点处理 Promise 拒绝,可能比触发 'unhandledRejection' 事件所需的事件循环更晚。

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

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

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

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

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

'uncaughtException' 事件#


  • err <Error> The uncaught exception.
  • origin <string> Indicates if the exception originates from an unhandled rejection or from synchronous errors. Can either be 'uncaughtException' or 'unhandledRejection'.

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.

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

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

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

警告: 正确地使用 'uncaughtException'#


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

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

Attempting to resume normally after an uncaught exception can be similar to pulling out of the power cord when upgrading a computer — nine out of ten times nothing happens - but the 10th time, the system becomes corrupted.

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

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.

'unhandledRejection' 事件#


  • reason <Error> | <any> The object with which the promise was rejected (typically an Error object).
  • promise <Promise> The rejected 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.

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

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

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

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' 事件#


  • 'warning'事件监听器的回调函数,参数只有一个,其值为Error 对象。此对象有三个重要的属性用来描述告警:

    • name <string> 告警的名称(目前默认值是 Warning)。
    • message <string> 系统提供的对此告警的描述。
    • stack <string> 当告警触发时,包含代码位置的堆栈信息。


进程告警与进程错误的相似之处,在于两者都描述了需要引起用户注意的异常条件。 区别在于,告警不是Node.js和Javascript错误处理流程的正式组成部分。 一旦探测到可能导致应用性能问题,缺陷或安全隐患相关的代码实践,Node.js就可发出告警。

process.on('warning', (warning) => {
  console.warn(;    // 打印告警名称
  console.warn(warning.message); // 打印告警信息
  console.warn(warning.stack);   // 打印堆栈信息

默认Node.js会打印进程告警到stderr。使用--no-warnings的命令行选项可以阻止默认从console输出信息, 但是'warning'事件仍然会被process对象发出。


$ 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


$ 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!


使用--throw-deprecation命令行选项标志启动Node.js,会使得custom deprecation warning作为异常信息抛出来。

使用--trace-deprecation命令行选项标志,会使得custom deprecation warning打印到stderr,包括其堆栈信息。

使用--no-deprecation命令行选项标志,会阻止报告所有的custom deprecation warning。

*-deprecation 命令行选项标志,只会影响使用名字为DeprecationWarning的告警。






当Node.js进程接收到一个信号时,会触发信号事件。 signal(7)列出了标准POSIX的信号名称列表,例如SIGINT, SIGHUP等等。

每个事件名称,以信号名称的大写表示 (比如事件'SIGINT' 对应信号 SIGINT).

// Begin reading from stdin so the process does not exit.

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保留用于启动调试器。可以为此事件绑定一个监听器,但是即使这样做也不会阻止调试器的启动。

  • SIGTERMSIGINT 在非windows平台绑定了默认的监听器,这样进程以代码128 + signal number结束之前,可以重置终端模式。  如果这两个事件任意一个绑定了新的监听器,原有默认的行为会被移除(Node.js不会结束)。

  • SIGPIPE 默认会被忽略。可以给其绑定监听器。

  • SIGHUP 在Windows平台中当console窗口被关闭时会触发它,在非windows平台中多种相似的条件下也会触发,查看signal(7)。 可以给其绑定监听器,但是Windows下Node.js会在它触发后10秒钟无条件关闭。 非windows平台, SIGHUP默认的绑定行为是结束Node.js,但是一旦给它绑定了新的监听器,默认行为会被移除。

  • SIGTERM 在Windows中不支持,可以给其绑定监听器。

  • SIGINT 在终端运行时,可以被所有平台支持,通常可以通过 <Ctrl>+C 触发(虽然这个不能配置)。 当终端运行在raw模式,它不会被触发。

  • SIGBREAK 在Windows中按下<Ctrl>+<Break>会被触发,非Windows平台中可以为其绑定监听器,但是没有方式触发或发送此事件。

  • SIGWINCH 当console被resize时会触发。Windows中只有当光标移动并写入到console,或者以raw模式使用一个可读tty时,才会触发。

  • SIGKILL 不能绑定监听器,所有平台中出现此事件,都会使得Node.js无条件终止。

  • SIGSTOP 不能绑定监听器。

  • SIGBUS, SIGFPE, SIGSEGV and SIGILL, 如果不是通过kill(2)产生,默认会使进程停留在某个状态,在此状态下尝试调用JS监听器是不安全的。 如果尝试调用JS监听器可能会导致进程在无限循环中挂死,因为使用process.on()附加的监听器是以异步的方式被调用,因此不能纠正隐含的问题。

Note: Windows不支持发送信号,但是Node.js通过process.kill(), 和 subprocess.kill()提供了某些模拟机制。 发送信号0 可以测试进程是否存在。发送SIGINT, SIGTERM, and SIGKILL 使得目标进程无条件终止。






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

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

  • Flags may omit leading single (-) or double (--) dashes; e.g., inspect-brk for --inspect-brk, or r for -r.
  • Flags passed through to V8 (as listed in --v8-options) may replace one or more non-leading dashes for an underscore, or vice-versa; e.g., --perf_basic_prof, --perf-basic-prof, --perf_basic-prof, etc.
  • Flags may contain one or more equals (=) characters; all characters after and including the first equals will be ignored; e.g., --stack-trace-limit=100.
  • Flags must be allowable within NODE_OPTIONS.

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:

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

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

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



process.arch属性返回一个表示操作系统CPU架构的字符串,Node.js二进制文件是为这些架构编译的。 例如 'arm', 'arm64', 'ia32', 'mips', 'mipsel', 'ppc', 'ppc64', 's390', 's390x', 'x32', 或 'x64'

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



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

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

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

启动 Node.js 进程:

$ node process-args.js one two=three four


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



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

$ bash -c 'exec -a customArgv0 ./node'
> process.argv[0]
> process.argv0


如果Node.js进程是由IPC channel(请看 Child Process 文档) 方式创建的, process.channel属性保存IPC channel的引用。 如果IPC channel不存在,此属性值为undefined




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



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:

   { cflags: [],
     default_configuration: 'Release',
     defines: [],
     include_dirs: [],
     libraries: [] },
     host_arch: 'x64',
     napi_build_version: 4,
     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

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.



如果Node.js进程是由IPC channel方式创建的(请看[Child Process子进程][] 和 [Cluster集群][] 文档), 只要IPC channel保持连接, process.connected属性就会返回trueprocess.disconnect()被调用后,此属性会返回false

process.connected如果为false,则不能通过IPC channel使用process.send()发送信息。



process.cpuUsage()方法返回包含当前进程的用户CPU时间和系统CPU时间的对象。此对象包含usersystem属性,属性值的单位都是微秒(百万分之一秒)。 usersystem属性值分别计算了执行用户程序和系统程序的时间,如果此进程在执行任务时是基于多核CPU,值可能比实际花费的时间要大。


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

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

// { user: 514883, system: 11226 }



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

console.log(`当前工作目录是: ${process.cwd()}`);



debugger 调试器使用的端口。

process.debugPort = 5858;



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.

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

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

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


The process.dlopen() method allows to dynamically load 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.

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

If there are specific reasons to use process.dlopen() (for instance, to specify dlopen flags), it's often useful to use require.resolve() to look up the module's path.

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

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

const os = require('os');
process.dlopen(module, require.resolve('binding'),

process.emitWarning(warning[, options])#


  • warning <string> | <Error> 发出的警告。
  • options <Object>

    • type <string> 如果 warning 是String, type 是警告类型的名字。 默认值: Warning
    • code <string> 当前警告的唯一标识符。
    • ctor <Function> 如果warning是String, ctor是可选的function,用于限制生成的堆栈信息。默认process.emitWarning
    • detail <string> error的附加信息。

process.emitWarning()方法可用于发出定制的或应用特定的进程警告。 可以通过给process.on('warning')事件增加处理器,监听这些警告。

// Emit a warning with a code and additional detail.
process.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

在上面例子中, process.emitWarning()内部生成了一个Error对象,并传递给process.on('warning')事件。

process.on('warning', (warning) => {
  console.warn(;    // '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参数项都会被忽略。

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


  • warning <string> | <Error> The warning to emit.
  • type <string> When warning is a String, type is the name to use for the type of warning being emitted. Default: 'Warning'.
  • code <string> A unique identifier for the warning instance being emitted.
  • ctor <Function> When warning is a String, ctor is an optional function used to limit the generated stack trace. Default: process.emitWarning.

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.

// Emit a warning using a string.
process.emitWarning('Something happened!');
// Emits: (node: 56338) Warning: Something happened!
// Emit a warning using a string and a type.
process.emitWarning('Something Happened!', 'CustomWarning');
// Emits: (node:56338) CustomWarning: Something Happened!
process.emitWarning('Something happened!', 'CustomWarning', 'WARN001');
// Emits: (node:56338) [WARN001] CustomWarning: Something happened!

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

process.on('warning', (warning) => {

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

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

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

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

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

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

  • If the --throw-deprecation command-line flag is used, the deprecation warning is thrown as an exception rather than being emitted as an event.
  • If the --no-deprecation command-line flag is used, the deprecation warning is suppressed.
  • If the --trace-deprecation command-line flag is used, the deprecation warning is printed to stderr along with the full stack trace.



作为最佳实践,警告应该在每个进程中最多发出一次。 为了达到上述的要求,推荐在使用emitWarning()之前用一个简单的布尔值做判断,如下例所示:

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



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'

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 ' = "bar"' && echo $foo

While the following will: = 'bar';

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.

process.env.test = null;
// => 'null'
process.env.test = undefined;
// => 'undefined'

Use delete to delete a property from process.env.

process.env.TEST = 1;
delete process.env.TEST;
// => undefined

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

process.env.TEST = 1;
// => 1

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.



process.execArgv 属性返回当Node.js进程被启动时,Node.js特定的命令行选项。 这些选项在process.argv属性返回的数组中不会出现,并且这些选项中不会包括Node.js的可执行脚本名称或者任何在脚本名称后面出现的选项。 这些选项在创建子进程时是有用的,因为他们包含了与父进程一样的执行环境信息。


$ node --harmony script.js --version




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



process.execPath 属性返回启动 Node.js 进程的可执行文件的绝对路径名。




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



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

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

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

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

// 这是一个错误用法的示例:
if (someConditionNotMet()) {

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

代码不应直接调用 process.exit(),而应设置 process.exitCode 并允许进程自然退出,避免为事件循环调度任何其他工作:

// 如何正确设置退出码,同时让进程正常退出。
if (someConditionNotMet()) {
  process.exitCode = 1;

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

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



当进程正常退出,或通过 process.exit() 退出且未指定退出码时,此数值将作为进程的退出码。

指定 process.exit(code) 的退出码将覆盖 process.exitCode 的原有设置。



process.getegid()方法返回Node.js进程的有效数字标记的组身份(See getegid(2))。

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




process.geteuid()方法返回Node.js进程的有效数字标记的用户身份(See geteuid(2))。

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




process.getgid()方法返回Node.js进程的数字标记的组身份(See getgid(2))。

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




process.getgroups()方法返回数组,其中包含了补充的组ID。 如果包含有效的组ID,POSIX会将其保留为未指定状态,但 Node.js 会确保它始终处于状态。




process.getuid()方法返回Node.js进程的数字标记的用户身份(See getuid(2))。

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




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



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

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

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

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

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

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



The bigint version of the process.hrtime() method returning the current high-resolution real time in a 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.

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

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

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

process.initgroups(user, extraGroup)#


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:

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

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> 将发送的信号,类型为string或number。默认为'SIGTERM'


信号名称是如'SIGINT''SIGHUP'的字符串。更多信息,查看Signal Eventskill(2)

如果目标pid不存在,该方法会抛出错误。作为一个特殊例子,信号0可以用于测试进程是否存在。 在Windows平台中,如果pid用于kill进程组,会抛出错误。

注意:即使这个函数的名称是process.kill(),它其实只是发送信号,这点与kill系统调用类似。 发送的信号可能是做一些与kill目标进程无关的事情。


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

setTimeout(() => {
}, 100);

process.kill(, 'SIGHUP');

注意: 当Node.js进程接收到了SIGUSR1,Node.js会启动debugger,查看Signal Events



process.mainModule属性提供了一种获取require.main的替代方式。 区别在于,若主模块在运行时中发生改变, require.main可能仍然指向变化之前所依赖的模块 一般来说,假定require.mainprocess.mainModule引用相同的模块是安全的。

就像require.main一样,如果没有入口脚本, process.mainModule的值是undefined







  rss: 4935680,
  heapTotal: 1826816,
  heapUsed: 650472,
  external: 49879

heapTotalheapUsed 代表V8的内存使用情况。 external代表V8管理的,绑定到Javascript的C++对象的内存使用情况。 rss, 驻留集大小, 是给这个进程分配了多少物理内存(占总分配内存的一部分) 这些物理内存中包含堆,栈,和代码段。

对象,字符串,闭包等存于堆内存。 变量存于栈内存。 实际的JavaScript源代码存于代码段内存。

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


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

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

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

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:

function MyThing(options) {

  process.nextTick(() => {

const thing = new MyThing();

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

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

function maybeSync(arg, cb) {
  if (arg) {

  fs.stat('file', cb);

This API is hazardous because in the following case:

const maybeTrue = Math.random() > 0.5;

maybeSync(maybeTrue, () => {


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

The following approach is much better:

function definitelyAsync(arg, cb) {
  if (arg) {

  fs.stat('file', cb);



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.



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





  • 'aix'
  • 'darwin'
  • 'freebsd'
  • 'linux'
  • 'openbsd'
  • 'sunos'
  • 'win32'
console.log(`This platform is ${process.platform}`);

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][supported platforms].



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

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



process.release 属性返回与当前发布相关的元数据对象,包括源代码和源代码头文件 tarball的URLs。


  • name <string> 对于Node.js, 此值始终为'node'。对于传统io.js 发布包, 此值为'io.js'

  • sourceUrl <string> 指向一个.tar.gz文件的绝对URL,包括了当前发布的源代码。

  • headersUrl<string> 指向一个.tar.gz文件的绝对URL,包括了当前发布的源代码的头文件信息。 这个文件要比全部源代码文件明显小很多,可以用于编译Node.js原生插件。

  • libUrl <string> 指向一个node.lib文件的绝对URL,匹配当前发布的结构和版本信息。此文件用于编译Node.js本地插件。 _这个属性只在Windows版本中存在,在其他平台中无效。

  • lts <string> 标识当前发布的LTS标签的字符串。  只有长效版(Long Term Support/LTS)存在这个属性,其他所有版本类型这个属性都是undefined,  包括Current版本,当前的有效值有:

    • 'Argon' for the 4.x LTS line beginning with 4.2.0.
    • 'Boron' for the 6.x LTS line beginning with 6.9.0.
    • 'Carbon' for the 8.x LTS line beginning with 8.9.1.


  name: 'node',
  lts: 'Argon',
  sourceUrl: '',
  headersUrl: '',
  libUrl: ''


暂无中英对照 is an object whose methods are used to generate diagnostic reports for the current process. Additional documentation is available in the report documentation.


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.

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


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.

console.log(`Report filename is ${}`);[err])#


  • err <Error> A custom error used for reporting the JavaScript stack.
  • Returns: <string>

Returns a JSON-formatted diagnostic report for the running process. The report's JavaScript stack trace is taken from err, if present.

const data =;

Additional documentation is available in the report documentation.


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

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


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

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


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

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


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

console.log(`Report signal: ${}`);[filename][, err])#


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

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

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

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

Additional documentation is available in the report documentation.



The process.resourceUsage() method returns the resource usage for the current process. All of these values come from the uv_getrusage call which returns this struct, here the mapping between node and libuv:

  • userCPUTime maps to ru_utime computed in microseconds. It is the values as process.cpuUsage().user
  • systemCPUTime maps to ru_stime computed in microseconds. It is the value as process.cpuUsage().system
  • maxRSS maps to ru_maxrss which is the maximum resident set size used (in kilobytes).
  • sharedMemorySize maps to ru_ixrss but is not supported by any platform.
  • unsharedDataSize maps to ru_idrss but is not supported by any platform.
  • unsharedStackSize maps to ru_isrss but is not supported by any platform.
  • minorPageFault maps to ru_minflt which is the number of minor page fault for the process, see this article for more details
  • majorPageFault maps to ru_majflt which is the number of major page fault for the process, see this article for more details. This field is not supported on Windows platforms.
  • swappedOut maps to ru_nswap which is not supported by any platform.
  • fsRead maps to ru_inblock which is the number of times the file system had to perform input.
  • fsWrite maps to ru_oublock which is the number of times the file system had to perform output.
  • ipcSent maps to ru_msgsnd but is not supported by any platform.
  • ipcReceived maps to ru_msgrcv but is not supported by any platform.
  • signalsCount maps to ru_nsignals but is not supported by any platform.
  • voluntaryContextSwitches maps to ru_nvcsw which is the number of times a CPU context switch resulted due to a process voluntarily giving up the processor before its time slice was completed (usually to await availability of a resource). This field is not supported on Windows platforms.
  • involuntaryContextSwitches maps to ru_nivcsw which is the number of times a CPU context switch resulted due to a higher priority process becoming runnable or because the current process exceeded its time slice. This field is not supported on Windows platforms.
  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进程是通过进程间通信产生的,那么,process.send()方法可以用来给父进程发送消息。 接收到的消息被视为父进程的ChildProcess对象上的一个'message'事件。

如果Node.js进程不是通过进程间通信产生的, process.send() 会是undefined

注意: 消息传递时,以格式序列化和解析,结果消息与发送时未必完全一样。



process.setegid()方法为进程设置有效的用户组ID。(请看 setegid(2).) id可以传一个数值ID或传一个用户组名称字符串。如果传了后者的话,会解析成一个相关的数值ID, 解析的时候,这个方法方法是阻塞的。

if (process.getegid && process.setegid) {
  console.log(`Current gid: ${process.getegid()}`);
  try {
    console.log(`New gid: ${process.getegid()}`);
  } catch (err) {
    console.log(`Failed to set gid: ${err}`);

注意: 这个方法只在POSIX平台可用(换句话说,Windows或Android不行)。



process.seteuid()方法为进程设置有效的用户ID。(请看 seteuid(2).) id可以传一个数值ID或传一个用户名字符串。如果传了特定的用户名字符串,会解析成一个相关的数值ID, 解析的时候,这个方法方法是阻塞的。

if (process.geteuid && process.seteuid) {
  console.log(`Current uid: ${process.geteuid()}`);
  try {
    console.log(`New uid: ${process.geteuid()}`);
  } catch (err) {
    console.log(`Failed to set uid: ${err}`);

注意: 这个方法只在POSIX平台可用(换句话说,Windows或Android不行)。



process.setgid() 为进程方法设置组ID. (查看setgid(2).) 可给id参数传一个数值ID或字符串名。


if (process.getgid && process.setgid) {
  console.log(`Current gid: ${process.getgid()}`);
  try {
    console.log(`New gid: ${process.getgid()}`);
  } catch (err) {
    console.log(`Failed to set gid: ${err}`);

注意: 这个方法只在POSIX平台可用(换句话说,Windows或Android不行)。



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.

The groups array can contain numeric group IDs, group names or both.

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) 设置进程的用户ID (参阅 setuid(2).) id 可以是一个数值ID也可以是一个用户名字符串. 如果已经有一个用户名,在解析为相关的数值ID时,此方法阻塞。

if (process.getuid && process.setuid) {
  console.log(`Current uid: ${process.getuid()}`);
  try {
    console.log(`New uid: ${process.getuid()}`);
  } catch (err) {
    console.log(`Failed to set uid: ${err}`);

注意: 这个方法只在POSIX平台可用(换句话说,Windows或Android不行)。



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.

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.

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.

Using this function is mutually exclusive with using the deprecated domain built-in module.



process.stderr 属性返回连接到 stderr (fd 2) 的流。 它是一个 net.Socket 流(也就是双工流),除非 fd 2 指向一个文件,在这种情况下它是一个可写流

process.stderr 与其他的 Node.js 流有重大区别。 有关更多信息,参阅有关进程 I/O 的注意事项



process.stdin 属性返回连接到 stdin (fd 0) 的流。 它是一个 net.Socket 流(也就是双工流),除非 fd 0 指向一个文件,在这种情况下它是一个可读流


process.stdin.on('readable', () => {
  const chunk =;
  if (chunk !== null) {
    process.stdout.write(`数据: ${chunk}`);

process.stdin.on('end', () => {

作为双工流process.stdin 也可以在“旧”模式下使用,该模式与在 v0.10 之前为 Node.js 编写的脚本兼容。 有关更多信息,参阅流的兼容性

在“旧”的流模式下,默认情况下 stdin 流是暂停的,因此必须调用 process.stdin.resume() 从中读取。 注意,调用 process.stdin.resume() 本身会将流切换为“旧”模式。



process.stdout 属性返回连接到 stdout (fd 1) 的流。 它是一个 net.Socket 流(也就是双工流),除非 fd 1 指向一个文件,在这种情况下它是一个可写流

例如,要将 process.stdin 拷贝到 process.stdout


process.stdout 与其他的 Node.js 流有重大区别。 有关更多信息,参阅有关进程 I/O 的注意事项

进程 I/O 的注意事项#


process.stdout and process.stderr 与 Node.js 中其他 streams 在重要的方面有不同:

  1. console.log()console.error() 内部分别是由它们实现的。

  2. 他们不能被关闭 (调用[end()][]将会抛出异常)。

  3. 他们永远不会触发 ['finish'][] 事件。

  4. 写操作是否为同步,取决于连接的是什么流以及操作系统是 Windows 还是 POSIX :

    • Files: 同步 在 Windows 和 POSIX 下
    • TTYs (Terminals): 异步 在 Windows 下, 同步 在 POSIX 下
    • Pipes (and sockets): 同步 在 Windows 下, 异步 在 POSIX 下


同步写避免了调用 console.log()console.error() 产生不符合预期的交错输出问题,或是在异步写完成前调用了process.exit()导致未写完整。 查看process.exit() 获取更多信息。

警告: 同步写将会阻塞事件循环直到写完成。 有时可能一瞬间就能写到一个文件,但当系统处于高负载时,管道的接收端可能不会被读取、缓慢的终端或文件系统,因为事件循环被阻塞的足够频繁且足够长的时间,这些可能会给系统性能带来消极的影响。当你向一个交互终端会话写时这可能不是个问题,但当生产日志到进程的输出流时要特别留心。

如果要检查一个流是否连接到了一个 TTY 上下文, 检查 isTTY 属性。


$ node -p "Boolean(process.stdin.isTTY)"
$ echo "foo" | node -p "Boolean(process.stdin.isTTY)"
$ node -p "Boolean(process.stdout.isTTY)"
$ node -p "Boolean(process.stdout.isTTY)" | cat

查看 TTY 文档以获得更多信息。



process.throwDeprecation 属性表示--throw-deprecation标记是否被设置到当前Node.js进程上。 请查看 warning eventemitWarning method 的文档, 来获取这个标记行为的更多信息。



process.title 属性用于获取或设置当前进程在 ps 命令中显示的进程名字

注意:当分配新值时,不同的平台会对标题施加不同的最大长度限制。 通常这种限制是相当有限的。 例如,在 Linux 和 macOS 上, process.title 仅限于二进制名称的大小加上命令行参数的长度,因为设置 process.title 会覆盖进程的argv内存。Node.js 的 v0.8, 通过覆盖 environ 允许内存较长的过程标题字符串,但是这在一些(相当模糊的)可能是不安全的并且令人困惑情况下。



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.



The process.umask() method sets or returns the Node.js process's file mode creation mask. Child processes inherit the mask from the parent process. Invoked without an argument, the current mask is returned, otherwise the umask is set to the argument value and the previous mask is returned.

const newmask = 0o022;
const oldmask = process.umask(newmask);
  `Changed umask from ${oldmask.toString(8)} to ${newmask.toString(8)}`

Worker threads are able to read the umask, however attempting to set the umask will result in a thrown exception.



process.uptime() 方法返回当前 Node.js 进程运行时间秒长

注意: 该返回值包含秒的分数。 使用 Math.floor() 来得到整秒钟。



process.version 属性返回Node.js的版本信息。

console.log(`Version: ${process.version}`);



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.


Will generate an object similar to:

{ node: '11.13.0',
  v8: '',
  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',
  http_parser: '2.8.0',
  openssl: '1.1.1b',
  cldr: '34.0',
  icu: '63.1',
  tz: '2018e',
  unicode: '11.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 Uncaught Fatal Exception - There was an uncaught exception, and it was not handled by a domain or an 'uncaughtException' event handler.
  • 2 - Unused (reserved by Bash for builtin misuse)
  • 3 Internal JavaScript Parse Error - The JavaScript source code internal in Node.js's bootstrapping process caused a parse error. This is extremely rare, and generally can only happen during development of Node.js itself.
  • 4 Internal JavaScript Evaluation Failure - The JavaScript source code internal in Node.js's bootstrapping process failed to return a function value when evaluated. This is extremely rare, and generally can only happen during development of Node.js itself.
  • 5 Fatal Error - There was a fatal unrecoverable error in V8. Typically a message will be printed to stderr with the prefix FATAL ERROR.
  • 6 Non-function Internal Exception Handler - There was an uncaught exception, but the internal fatal exception handler function was somehow set to a non-function, and could not be called.
  • 7 Internal Exception Handler Run-Time Failure - There was an uncaught exception, and the internal fatal exception handler function itself threw an error while attempting to handle it. This can happen, for example, if an 'uncaughtException' or domain.on('error') handler throws an error.
  • 8 - Unused. In previous versions of Node.js, exit code 8 sometimes indicated an uncaught exception.
  • 9 - Invalid Argument - Either an unknown option was specified, or an option requiring a value was provided without a value.
  • 10 Internal JavaScript Run-Time Failure - The JavaScript source code internal in Node.js's bootstrapping process threw an error when the bootstrapping function was called. This is extremely rare, and generally can only happen during development of Node.js itself.
  • 12 Invalid Debug Argument - The --inspect and/or --inspect-brk options were set, but the port number chosen was invalid or unavailable.
  • >128 Signal Exits - If Node.js receives a fatal signal such as SIGKILL or SIGHUP, then its exit code will be 128 plus the value of the signal code. This is a standard POSIX practice, since exit codes are defined to be 7-bit integers, and signal exits set the high-order bit, and then contain the value of the signal code. For example, signal SIGABRT has value 6, so the expected exit code will be 128 + 6, or 134.