{ "type": "module", "source": "doc/api/process.md", "globals": [ { "textRaw": "Process", "name": "Process", "introduced_in": "v0.10.0", "type": "global", "desc": "

The process object is a global that provides information about, and control\nover, the current Node.js process. As a global, it is always available to\nNode.js applications without using require().

", "modules": [ { "textRaw": "Process Events", "name": "process_events", "desc": "

The process object is an instance of EventEmitter.

", "events": [ { "textRaw": "Event: 'beforeExit'", "type": "event", "name": "beforeExit", "meta": { "added": [ "v0.11.12" ], "changes": [] }, "params": [], "desc": "

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

\n

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

\n

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

\n

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

" }, { "textRaw": "Event: 'disconnect'", "type": "event", "name": "disconnect", "meta": { "added": [ "v0.7.7" ], "changes": [] }, "params": [], "desc": "

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

" }, { "textRaw": "Event: 'exit'", "type": "event", "name": "exit", "meta": { "added": [ "v0.1.7" ], "changes": [] }, "params": [ { "textRaw": "`code` {integer}", "name": "code", "type": "integer" } ], "desc": "

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

\n\n

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

\n

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

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

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

\n
process.on('exit', (code) => {\n  setTimeout(() => {\n    console.log('This will not run');\n  }, 0);\n});\n
" }, { "textRaw": "Event: 'message'", "type": "event", "name": "message", "meta": { "added": [ "v0.5.10" ], "changes": [] }, "params": [ { "textRaw": "`message` { Object | boolean | number | string | null } a parsed JSON object or a serializable primitive value.", "name": "message", "type": " Object | boolean | number | string | null ", "desc": "a parsed JSON object or a serializable primitive value." }, { "textRaw": "`sendHandle` {net.Server|net.Socket} a [`net.Server`][] or [`net.Socket`][] object, or undefined.", "name": "sendHandle", "type": "net.Server|net.Socket", "desc": "a [`net.Server`][] or [`net.Socket`][] object, or undefined." } ], "desc": "

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

\n

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

" }, { "textRaw": "Event: 'multipleResolves'", "type": "event", "name": "multipleResolves", "meta": { "added": [ "v10.12.0" ], "changes": [] }, "params": [ { "textRaw": "`type` {string} The error type. One of `'resolve'` or `'reject'`.", "name": "type", "type": "string", "desc": "The error type. One of `'resolve'` or `'reject'`." }, { "textRaw": "`promise` {Promise} The promise that resolved or rejected more than once.", "name": "promise", "type": "Promise", "desc": "The promise that resolved or rejected more than once." }, { "textRaw": "`value` {any} The value with which the promise was either resolved or rejected after the original resolve.", "name": "value", "type": "any", "desc": "The value with which the promise was either resolved or rejected after the original resolve." } ], "desc": "

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

\n\n

This is useful for tracking errors in an application while using the promise\nconstructor. Otherwise such mistakes are silently swallowed due to being in a\ndead zone.

\n

It is recommended to end the process on such errors, since the process could be\nin an undefined state. While using the promise constructor make sure that it is\nguaranteed to trigger the resolve() or reject() functions exactly once per\ncall and never call both functions in the same call.

\n
process.on('multipleResolves', (type, promise, reason) => {\n  console.error(type, promise, reason);\n  setImmediate(() => process.exit(1));\n});\n\nasync function main() {\n  try {\n    return await new Promise((resolve, reject) => {\n      resolve('First call');\n      resolve('Swallowed resolve');\n      reject(new Error('Swallowed reject'));\n    });\n  } catch {\n    throw new Error('Failed');\n  }\n}\n\nmain().then(console.log);\n// resolve: Promise { 'First call' } 'Swallowed resolve'\n// reject: Promise { 'First call' } Error: Swallowed reject\n//     at Promise (*)\n//     at new Promise (<anonymous>)\n//     at main (*)\n// First call\n
" }, { "textRaw": "Event: 'rejectionHandled'", "type": "event", "name": "rejectionHandled", "meta": { "added": [ "v1.4.1" ], "changes": [] }, "params": [ { "textRaw": "`promise` {Promise} The late handled promise.", "name": "promise", "type": "Promise", "desc": "The late handled promise." } ], "desc": "

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

\n

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

\n

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

\n

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

\n

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

\n

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

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

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

" }, { "textRaw": "Event: 'uncaughtException'", "type": "event", "name": "uncaughtException", "meta": { "added": [ "v0.1.18" ], "changes": [ { "version": "v10.17.0", "pr-url": "https://github.com/nodejs/node/pull/26599", "description": "Added the `origin` argument." } ] }, "params": [ { "textRaw": "`err` {Error} The uncaught exception.", "name": "err", "type": "Error", "desc": "The uncaught exception." }, { "textRaw": "`origin` {string} Indicates if the exception originates from an unhandled rejection or from synchronous errors. Can either be `'uncaughtException'` or `'unhandledRejection'`.", "name": "origin", "type": "string", "desc": "Indicates if the exception originates from an unhandled rejection or from synchronous errors. Can either be `'uncaughtException'` or `'unhandledRejection'`." } ], "desc": "

The 'uncaughtException' event is emitted when an uncaught JavaScript\nexception bubbles all the way back to the event loop. By default, Node.js\nhandles such exceptions by printing the stack trace to stderr and exiting\nwith code 1, overriding any previously set process.exitCode.\nAdding a handler for the 'uncaughtException' event overrides this default\nbehavior. Alternatively, change the process.exitCode in the\n'uncaughtException' handler which will result in the process exiting with the\nprovided exit code. Otherwise, in the presence of such handler the process will\nexit with 0.

\n
process.on('uncaughtException', (err, origin) => {\n  fs.writeSync(\n    process.stderr.fd,\n    `Caught exception: ${err}\\n` +\n    `Exception origin: ${origin}`\n  );\n});\n\nsetTimeout(() => {\n  console.log('This will still run.');\n}, 500);\n\n// Intentionally cause an exception, but don't catch it.\nnonexistentFunc();\nconsole.log('This will not run.');\n
", "modules": [ { "textRaw": "Warning: Using `'uncaughtException'` correctly", "name": "warning:_using_`'uncaughtexception'`_correctly", "desc": "

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

\n

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

\n

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

\n

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

\n

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

", "type": "module", "displayName": "Warning: Using `'uncaughtException'` correctly" } ] }, { "textRaw": "Event: 'unhandledRejection'", "type": "event", "name": "unhandledRejection", "meta": { "added": [ "v1.4.1" ], "changes": [ { "version": "v7.0.0", "pr-url": "https://github.com/nodejs/node/pull/8217", "description": "Not handling `Promise` rejections is deprecated." }, { "version": "v6.6.0", "pr-url": "https://github.com/nodejs/node/pull/8223", "description": "Unhandled `Promise` rejections will now emit a process warning." } ] }, "params": [ { "textRaw": "`reason` {Error|any} The object with which the promise was rejected (typically an [`Error`][] object).", "name": "reason", "type": "Error|any", "desc": "The object with which the promise was rejected (typically an [`Error`][] object)." }, { "textRaw": "`promise` {Promise} The rejected promise.", "name": "promise", "type": "Promise", "desc": "The rejected promise." } ], "desc": "

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

\n
process.on('unhandledRejection', (reason, promise) => {\n  console.log('Unhandled Rejection at:', promise, 'reason:', reason);\n  // Application specific logging, throwing an error, or other logic here\n});\n\nsomePromise.then((res) => {\n  return reportToUser(JSON.pasre(res)); // note the typo (`pasre`)\n}); // no `.catch()` or `.then()`\n
\n

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

\n
function SomeResource() {\n  // Initially set the loaded status to a rejected promise\n  this.loaded = Promise.reject(new Error('Resource not yet loaded!'));\n}\n\nconst resource = new SomeResource();\n// no .catch or .then on resource.loaded for at least a turn\n
\n

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

" }, { "textRaw": "Event: 'warning'", "type": "event", "name": "warning", "meta": { "added": [ "v6.0.0" ], "changes": [] }, "params": [ { "textRaw": "`warning` {Error} Key properties of the warning are:", "name": "warning", "type": "Error", "desc": "Key properties of the warning are:", "options": [ { "textRaw": "`name` {string} The name of the warning. **Default:** `'Warning'`.", "name": "name", "type": "string", "default": "`'Warning'`", "desc": "The name of the warning." }, { "textRaw": "`message` {string} A system-provided description of the warning.", "name": "message", "type": "string", "desc": "A system-provided description of the warning." }, { "textRaw": "`stack` {string} A stack trace to the location in the code where the warning was issued.", "name": "stack", "type": "string", "desc": "A stack trace to the location in the code where the warning was issued." } ] } ], "desc": "

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

\n

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

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

By default, Node.js will print process warnings to stderr. The --no-warnings\ncommand-line option can be used to suppress the default console output but the\n'warning' event will still be emitted by the process object.

\n

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

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

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

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

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

\n

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

\n

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

\n

Using the --no-deprecation command line flag will suppress all reporting\nof the custom deprecation.

\n

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

", "modules": [ { "textRaw": "Emitting custom warnings", "name": "emitting_custom_warnings", "desc": "

See the process.emitWarning() method for issuing\ncustom or application-specific warnings.

", "type": "module", "displayName": "Emitting custom warnings" } ] }, { "textRaw": "Signal Events", "name": "SIGINT, SIGHUP, etc.", "type": "event", "params": [], "desc": "

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

\n

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

\n

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

\n
// Begin reading from stdin so the process does not exit.\nprocess.stdin.resume();\n\nprocess.on('SIGINT', () => {\n  console.log('Received SIGINT. Press Control-D to exit.');\n});\n\n// Using a single function to handle multiple signals\nfunction handle(signal) {\n  console.log(`Received ${signal}`);\n}\n\nprocess.on('SIGINT', handle);\nprocess.on('SIGTERM', handle);\n
\n\n

Windows does not support sending signals, but Node.js offers some emulation\nwith process.kill(), and subprocess.kill(). Sending signal 0 can\nbe used to test for the existence of a process. Sending SIGINT, SIGTERM,\nand SIGKILL cause the unconditional termination of the target process.

" } ], "type": "module", "displayName": "Process Events" }, { "textRaw": "Exit Codes", "name": "exit_codes", "desc": "

Node.js will normally exit with a 0 status code when no more async\noperations are pending. The following status codes are used in other\ncases:

\n", "type": "module", "displayName": "Exit Codes" } ], "methods": [ { "textRaw": "process.abort()", "type": "method", "name": "abort", "meta": { "added": [ "v0.7.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

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

\n

This feature is not available in Worker threads.

" }, { "textRaw": "process.chdir(directory)", "type": "method", "name": "chdir", "meta": { "added": [ "v0.1.17" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`directory` {string}", "name": "directory", "type": "string" } ] } ], "desc": "

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

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

This feature is not available in Worker threads.

" }, { "textRaw": "process.cpuUsage([previousValue])", "type": "method", "name": "cpuUsage", "meta": { "added": [ "v6.1.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Object}", "name": "return", "type": "Object", "options": [ { "textRaw": "`user` {integer}", "name": "user", "type": "integer" }, { "textRaw": "`system` {integer}", "name": "system", "type": "integer" } ] }, "params": [ { "textRaw": "`previousValue` {Object} A previous return value from calling `process.cpuUsage()`", "name": "previousValue", "type": "Object", "desc": "A previous return value from calling `process.cpuUsage()`", "optional": true } ] } ], "desc": "

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

\n

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

\n
const startUsage = process.cpuUsage();\n// { user: 38579, system: 6986 }\n\n// spin the CPU for 500 milliseconds\nconst now = Date.now();\nwhile (Date.now() - now < 500);\n\nconsole.log(process.cpuUsage(startUsage));\n// { user: 514883, system: 11226 }\n
" }, { "textRaw": "process.cwd()", "type": "method", "name": "cwd", "meta": { "added": [ "v0.1.8" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {string}", "name": "return", "type": "string" }, "params": [] } ], "desc": "

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

\n
console.log(`Current directory: ${process.cwd()}`);\n
" }, { "textRaw": "process.disconnect()", "type": "method", "name": "disconnect", "meta": { "added": [ "v0.7.2" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

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

\n

The effect of calling process.disconnect() is that same as calling the parent\nprocess's ChildProcess.disconnect().

\n

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

" }, { "textRaw": "process.dlopen(module, filename[, flags])", "type": "method", "name": "dlopen", "meta": { "added": [ "v0.1.16" ], "changes": [ { "version": "v9.0.0", "pr-url": "https://github.com/nodejs/node/pull/12794", "description": "Added support for the `flags` argument." } ] }, "signatures": [ { "params": [ { "textRaw": "`module` {Object}", "name": "module", "type": "Object" }, { "textRaw": "`filename` {string}", "name": "filename", "type": "string" }, { "textRaw": "`flags` {os.constants.dlopen} **Default:** `os.constants.dlopen.RTLD_LAZY`", "name": "flags", "type": "os.constants.dlopen", "default": "`os.constants.dlopen.RTLD_LAZY`", "optional": true } ] } ], "desc": "

The process.dlopen() method allows to dynamically load shared\nobjects. It is primarily used by require() to load\nC++ Addons, and should not be used directly, except in special\ncases. In other words, require() should be preferred over\nprocess.dlopen(), unless there are specific reasons.

\n

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

\n

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

\n

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

\n

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

\n
const os = require('os');\nprocess.dlopen(module, require.resolve('binding'),\n               os.constants.dlopen.RTLD_NOW);\nmodule.exports.foo();\n
" }, { "textRaw": "process.emitWarning(warning[, options])", "type": "method", "name": "emitWarning", "meta": { "added": [ "v8.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`warning` {string|Error} The warning to emit.", "name": "warning", "type": "string|Error", "desc": "The warning to emit." }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`type` {string} When `warning` is a `String`, `type` is the name to use for the *type* of warning being emitted. **Default:** `'Warning'`.", "name": "type", "type": "string", "default": "`'Warning'`", "desc": "When `warning` is a `String`, `type` is the name to use for the *type* of warning being emitted." }, { "textRaw": "`code` {string} A unique identifier for the warning instance being emitted.", "name": "code", "type": "string", "desc": "A unique identifier for the warning instance being emitted." }, { "textRaw": "`ctor` {Function} When `warning` is a `String`, `ctor` is an optional function used to limit the generated stack trace. **Default:** `process.emitWarning`.", "name": "ctor", "type": "Function", "default": "`process.emitWarning`", "desc": "When `warning` is a `String`, `ctor` is an optional function used to limit the generated stack trace." }, { "textRaw": "`detail` {string} Additional text to include with the error.", "name": "detail", "type": "string", "desc": "Additional text to include with the error." } ], "optional": true } ] } ], "desc": "

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

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

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

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

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

" }, { "textRaw": "process.emitWarning(warning[, type[, code]][, ctor])", "type": "method", "name": "emitWarning", "meta": { "added": [ "v6.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`warning` {string|Error} The warning to emit.", "name": "warning", "type": "string|Error", "desc": "The warning to emit." }, { "textRaw": "`type` {string} When `warning` is a `String`, `type` is the name to use for the *type* of warning being emitted. **Default:** `'Warning'`.", "name": "type", "type": "string", "default": "`'Warning'`", "desc": "When `warning` is a `String`, `type` is the name to use for the *type* of warning being emitted.", "optional": true }, { "textRaw": "`code` {string} A unique identifier for the warning instance being emitted.", "name": "code", "type": "string", "desc": "A unique identifier for the warning instance being emitted.", "optional": true }, { "textRaw": "`ctor` {Function} When `warning` is a `String`, `ctor` is an optional function used to limit the generated stack trace. **Default:** `process.emitWarning`.", "name": "ctor", "type": "Function", "default": "`process.emitWarning`", "desc": "When `warning` is a `String`, `ctor` is an optional function used to limit the generated stack trace.", "optional": true } ] } ], "desc": "

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

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

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

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

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

\n
// Emit a warning using an Error object.\nconst myWarning = new Error('Something happened!');\n// Use the Error name property to specify the type name\nmyWarning.name = 'CustomWarning';\nmyWarning.code = 'WARN001';\n\nprocess.emitWarning(myWarning);\n// Emits: (node:56338) [WARN001] CustomWarning: Something happened!\n
\n

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

\n

Note that while process warnings use Error objects, the process warning\nmechanism is not a replacement for normal error handling mechanisms.

\n

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

\n", "modules": [ { "textRaw": "Avoiding duplicate warnings", "name": "avoiding_duplicate_warnings", "desc": "

As a best practice, warnings should be emitted only once per process. To do\nso, it is recommended to place the emitWarning() behind a simple boolean\nflag as illustrated in the example below:

\n
function emitMyWarning() {\n  if (!emitMyWarning.warned) {\n    emitMyWarning.warned = true;\n    process.emitWarning('Only warn once!');\n  }\n}\nemitMyWarning();\n// Emits: (node: 56339) Warning: Only warn once!\nemitMyWarning();\n// Emits nothing\n
", "type": "module", "displayName": "Avoiding duplicate warnings" } ] }, { "textRaw": "process.exit([code])", "type": "method", "name": "exit", "meta": { "added": [ "v0.1.13" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`code` {integer} The exit code. **Default:** `0`.", "name": "code", "type": "integer", "default": "`0`", "desc": "The exit code.", "optional": true } ] } ], "desc": "

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

\n

To exit with a 'failure' code:

\n
process.exit(1);\n
\n

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

\n

Calling process.exit() will force the process to exit as quickly as possible\neven if there are still asynchronous operations pending that have not yet\ncompleted fully, including I/O operations to process.stdout and\nprocess.stderr.

\n

In most situations, it is not actually necessary to call process.exit()\nexplicitly. The Node.js process will exit on its own if there is no additional\nwork pending in the event loop. The process.exitCode property can be set to\ntell the process which exit code to use when the process exits gracefully.

\n

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

\n
// This is an example of what *not* to do:\nif (someConditionNotMet()) {\n  printUsageToStdout();\n  process.exit(1);\n}\n
\n

The reason this is problematic is because writes to process.stdout in Node.js\nare sometimes asynchronous and may occur over multiple ticks of the Node.js\nevent loop. Calling process.exit(), however, forces the process to exit\nbefore those additional writes to stdout can be performed.

\n

Rather than calling process.exit() directly, the code should set the\nprocess.exitCode and allow the process to exit naturally by avoiding\nscheduling any additional work for the event loop:

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

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

\n

In Worker threads, this function stops the current thread rather\nthan the current process.

" }, { "textRaw": "process.getegid()", "type": "method", "name": "getegid", "meta": { "added": [ "v2.0.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

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

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

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

" }, { "textRaw": "process.geteuid()", "type": "method", "name": "geteuid", "meta": { "added": [ "v2.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Object}", "name": "return", "type": "Object" }, "params": [] } ], "desc": "

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

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

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

" }, { "textRaw": "process.getgid()", "type": "method", "name": "getgid", "meta": { "added": [ "v0.1.31" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Object}", "name": "return", "type": "Object" }, "params": [] } ], "desc": "

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

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

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

" }, { "textRaw": "process.getgroups()", "type": "method", "name": "getgroups", "meta": { "added": [ "v0.9.4" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {integer[]}", "name": "return", "type": "integer[]" }, "params": [] } ], "desc": "

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

\n

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

" }, { "textRaw": "process.getuid()", "type": "method", "name": "getuid", "meta": { "added": [ "v0.1.28" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {integer}", "name": "return", "type": "integer" }, "params": [] } ], "desc": "

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

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

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

" }, { "textRaw": "process.hasUncaughtExceptionCaptureCallback()", "type": "method", "name": "hasUncaughtExceptionCaptureCallback", "meta": { "added": [ "v9.3.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [] } ], "desc": "

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

" }, { "textRaw": "process.hrtime([time])", "type": "method", "name": "hrtime", "meta": { "added": [ "v0.7.6" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {integer[]}", "name": "return", "type": "integer[]" }, "params": [ { "textRaw": "`time` {integer[]} The result of a previous call to `process.hrtime()`", "name": "time", "type": "integer[]", "desc": "The result of a previous call to `process.hrtime()`", "optional": true } ] } ], "desc": "

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

\n

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

\n

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

\n

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

\n
const NS_PER_SEC = 1e9;\nconst time = process.hrtime();\n// [ 1800216, 25 ]\n\nsetTimeout(() => {\n  const diff = process.hrtime(time);\n  // [ 1, 552 ]\n\n  console.log(`Benchmark took ${diff[0] * NS_PER_SEC + diff[1]} nanoseconds`);\n  // benchmark took 1000000552 nanoseconds\n}, 1000);\n
" }, { "textRaw": "process.hrtime.bigint()", "type": "method", "name": "bigint", "meta": { "added": [ "v10.7.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {bigint}", "name": "return", "type": "bigint" }, "params": [] } ], "desc": "

The bigint version of the process.hrtime() method returning the\ncurrent high-resolution real time in a bigint.

\n

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

\n
const start = process.hrtime.bigint();\n// 191051479007711n\n\nsetTimeout(() => {\n  const end = process.hrtime.bigint();\n  // 191052633396993n\n\n  console.log(`Benchmark took ${end - start} nanoseconds`);\n  // Benchmark took 1154389282 nanoseconds\n}, 1000);\n
" }, { "textRaw": "process.initgroups(user, extraGroup)", "type": "method", "name": "initgroups", "meta": { "added": [ "v0.9.4" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`user` {string|number} The user name or numeric identifier.", "name": "user", "type": "string|number", "desc": "The user name or numeric identifier." }, { "textRaw": "`extraGroup` {string|number} A group name or numeric identifier.", "name": "extraGroup", "type": "string|number", "desc": "A group name or numeric identifier." } ] } ], "desc": "

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

\n

Note that care must be taken when dropping privileges:

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

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

" }, { "textRaw": "process.kill(pid[, signal])", "type": "method", "name": "kill", "meta": { "added": [ "v0.0.6" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`pid` {number} A process ID", "name": "pid", "type": "number", "desc": "A process ID" }, { "textRaw": "`signal` {string|number} The signal to send, either as a string or number. **Default:** `'SIGTERM'`.", "name": "signal", "type": "string|number", "default": "`'SIGTERM'`", "desc": "The signal to send, either as a string or number.", "optional": true } ] } ], "desc": "

The process.kill() method sends the signal to the process identified by\npid.

\n

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

\n

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

\n

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

\n
process.on('SIGHUP', () => {\n  console.log('Got SIGHUP signal.');\n});\n\nsetTimeout(() => {\n  console.log('Exiting.');\n  process.exit(0);\n}, 100);\n\nprocess.kill(process.pid, 'SIGHUP');\n
\n

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

" }, { "textRaw": "process.memoryUsage()", "type": "method", "name": "memoryUsage", "meta": { "added": [ "v0.1.16" ], "changes": [ { "version": "v7.2.0", "pr-url": "https://github.com/nodejs/node/pull/9587", "description": "Added `external` to the returned object." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Object}", "name": "return", "type": "Object", "options": [ { "textRaw": "`rss` {integer}", "name": "rss", "type": "integer" }, { "textRaw": "`heapTotal` {integer}", "name": "heapTotal", "type": "integer" }, { "textRaw": "`heapUsed` {integer}", "name": "heapUsed", "type": "integer" }, { "textRaw": "`external` {integer}", "name": "external", "type": "integer" } ] }, "params": [] } ], "desc": "

The process.memoryUsage() method returns an object describing the memory usage\nof the Node.js process measured in bytes.

\n

For example, the code:

\n
console.log(process.memoryUsage());\n
\n

Will generate:

\n\n
{\n  rss: 4935680,\n  heapTotal: 1826816,\n  heapUsed: 650472,\n  external: 49879\n}\n
\n

heapTotal and heapUsed refer to V8's memory usage.\nexternal refers to the memory usage of C++ objects bound to JavaScript\nobjects managed by V8. rss, Resident Set Size, is the amount of space\noccupied in the main memory device (that is a subset of the total allocated\nmemory) for the process, which includes the heap, code segment and stack.

\n

The heap is where objects, strings, and closures are stored. Variables are\nstored in the stack and the actual JavaScript code resides in the\ncode segment.

\n

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

" }, { "textRaw": "process.nextTick(callback[, ...args])", "type": "method", "name": "nextTick", "meta": { "added": [ "v0.1.26" ], "changes": [ { "version": "v1.8.1", "pr-url": "https://github.com/nodejs/node/pull/1077", "description": "Additional arguments after `callback` are now supported." } ] }, "signatures": [ { "params": [ { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" }, { "textRaw": "`...args` {any} Additional arguments to pass when invoking the `callback`", "name": "...args", "type": "any", "desc": "Additional arguments to pass when invoking the `callback`", "optional": true } ] } ], "desc": "

The process.nextTick() method adds the callback to the \"next tick queue\".\nOnce the current turn of the event loop turn runs to completion, all callbacks\ncurrently in the next tick queue will be called.

\n

This is not a simple alias to setTimeout(fn, 0). It is much more\nefficient. It runs before any additional I/O events (including\ntimers) fire in subsequent ticks of the event loop.

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

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

\n
function MyThing(options) {\n  this.setupOptions(options);\n\n  process.nextTick(() => {\n    this.startDoingStuff();\n  });\n}\n\nconst thing = new MyThing();\nthing.getReadyForStuff();\n\n// thing.startDoingStuff() gets called now, not before.\n
\n

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

\n
// WARNING!  DO NOT USE!  BAD UNSAFE HAZARD!\nfunction maybeSync(arg, cb) {\n  if (arg) {\n    cb();\n    return;\n  }\n\n  fs.stat('file', cb);\n}\n
\n

This API is hazardous because in the following case:

\n
const maybeTrue = Math.random() > 0.5;\n\nmaybeSync(maybeTrue, () => {\n  foo();\n});\n\nbar();\n
\n

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

\n

The following approach is much better:

\n
function definitelyAsync(arg, cb) {\n  if (arg) {\n    process.nextTick(cb);\n    return;\n  }\n\n  fs.stat('file', cb);\n}\n
\n

The next tick queue is completely drained on each pass of the event loop\nbefore additional I/O is processed. As a result, recursively setting\nnextTick() callbacks will block any I/O from happening, just like a\nwhile(true); loop.

" }, { "textRaw": "process.send(message[, sendHandle[, options]][, callback])", "type": "method", "name": "send", "meta": { "added": [ "v0.5.9" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`message` {Object}", "name": "message", "type": "Object" }, { "textRaw": "`sendHandle` {net.Server|net.Socket}", "name": "sendHandle", "type": "net.Server|net.Socket", "optional": true }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "optional": true }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "optional": true } ] } ], "desc": "

If Node.js is spawned with an IPC channel, the process.send() method can be\nused to send messages to the parent process. Messages will be received as a\n'message' event on the parent's ChildProcess object.

\n

If Node.js was not spawned with an IPC channel, process.send() will be\nundefined.

\n

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

" }, { "textRaw": "process.setegid(id)", "type": "method", "name": "setegid", "meta": { "added": [ "v2.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`id` {string|number} A group name or ID", "name": "id", "type": "string|number", "desc": "A group name or ID" } ] } ], "desc": "

The process.setegid() method sets the effective group identity of the process.\n(See setegid(2).) The id can be passed as either a numeric ID or a group\nname string. If a group name is specified, this method blocks while resolving\nthe associated a numeric ID.

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

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

" }, { "textRaw": "process.seteuid(id)", "type": "method", "name": "seteuid", "meta": { "added": [ "v2.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`id` {string|number} A user name or ID", "name": "id", "type": "string|number", "desc": "A user name or ID" } ] } ], "desc": "

The process.seteuid() method sets the effective user identity of the process.\n(See seteuid(2).) The id can be passed as either a numeric ID or a username\nstring. If a username is specified, the method blocks while resolving the\nassociated numeric ID.

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

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

" }, { "textRaw": "process.setgid(id)", "type": "method", "name": "setgid", "meta": { "added": [ "v0.1.31" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`id` {string|number} The group name or ID", "name": "id", "type": "string|number", "desc": "The group name or ID" } ] } ], "desc": "

The process.setgid() method sets the group identity of the process. (See\nsetgid(2).) The id can be passed as either a numeric ID or a group name\nstring. If a group name is specified, this method blocks while resolving the\nassociated numeric ID.

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

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

" }, { "textRaw": "process.setgroups(groups)", "type": "method", "name": "setgroups", "meta": { "added": [ "v0.9.4" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`groups` {integer[]}", "name": "groups", "type": "integer[]" } ] } ], "desc": "

The process.setgroups() method sets the supplementary group IDs for the\nNode.js process. This is a privileged operation that requires the Node.js\nprocess to have root or the CAP_SETGID capability.

\n

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

\n

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

" }, { "textRaw": "process.setuid(id)", "type": "method", "name": "setuid", "meta": { "added": [ "v0.1.28" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`id` {integer | string}", "name": "id", "type": "integer | string" } ] } ], "desc": "

The process.setuid(id) method sets the user identity of the process. (See\nsetuid(2).) The id can be passed as either a numeric ID or a username string.\nIf a username is specified, the method blocks while resolving the associated\nnumeric ID.

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

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

" }, { "textRaw": "process.setUncaughtExceptionCaptureCallback(fn)", "type": "method", "name": "setUncaughtExceptionCaptureCallback", "meta": { "added": [ "v9.3.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`fn` {Function|null}", "name": "fn", "type": "Function|null" } ] } ], "desc": "

The process.setUncaughtExceptionCaptureCallback() function sets a function\nthat will be invoked when an uncaught exception occurs, which will receive the\nexception value itself as its first argument.

\n

If such a function is set, the 'uncaughtException' event will\nnot be emitted. If --abort-on-uncaught-exception was passed from the\ncommand line or set through v8.setFlagsFromString(), the process will\nnot abort.

\n

To unset the capture function,\nprocess.setUncaughtExceptionCaptureCallback(null) may be used. Calling this\nmethod with a non-null argument while another capture function is set will\nthrow an error.

\n

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

" }, { "textRaw": "process.umask([mask])", "type": "method", "name": "umask", "meta": { "added": [ "v0.1.19" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`mask` {number}", "name": "mask", "type": "number", "optional": true } ] } ], "desc": "

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

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

This feature is not available in Worker threads.

" }, { "textRaw": "process.uptime()", "type": "method", "name": "uptime", "meta": { "added": [ "v0.5.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {number}", "name": "return", "type": "number" }, "params": [] } ], "desc": "

The process.uptime() method returns the number of seconds the current Node.js\nprocess has been running.

\n

The return value includes fractions of a second. Use Math.floor() to get whole\nseconds.

" } ], "properties": [ { "textRaw": "`allowedNodeEnvironmentFlags` {Set}", "type": "Set", "name": "allowedNodeEnvironmentFlags", "meta": { "added": [ "v10.10.0" ], "changes": [] }, "desc": "

The process.allowedNodeEnvironmentFlags property is a special,\nread-only Set of flags allowable within the NODE_OPTIONS\nenvironment variable.

\n

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

\n\n

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

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

The methods add(), clear(), and delete() of\nprocess.allowedNodeEnvironmentFlags do nothing, and will fail\nsilently.

\n

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

" }, { "textRaw": "`arch` {string}", "type": "string", "name": "arch", "meta": { "added": [ "v0.5.0" ], "changes": [] }, "desc": "

The process.arch property returns a string identifying the operating system\nCPU architecture for which the Node.js binary was compiled.

\n

The current possible values are: 'arm', 'arm64', 'ia32', 'mips',\n'mipsel', 'ppc', 'ppc64', 's390', 's390x', 'x32', and 'x64'.

\n
console.log(`This processor architecture is ${process.arch}`);\n
" }, { "textRaw": "`argv` {string[]}", "type": "string[]", "name": "argv", "meta": { "added": [ "v0.1.27" ], "changes": [] }, "desc": "

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

\n

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

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

Launching the Node.js process as:

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

Would generate the output:

\n
0: /usr/local/bin/node\n1: /Users/mjr/work/node/process-args.js\n2: one\n3: two=three\n4: four\n
" }, { "textRaw": "`argv0` {string}", "type": "string", "name": "argv0", "meta": { "added": [ "v6.4.0" ], "changes": [] }, "desc": "

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

\n
$ bash -c 'exec -a customArgv0 ./node'\n> process.argv[0]\n'/Volumes/code/external/node/out/Release/node'\n> process.argv0\n'customArgv0'\n
" }, { "textRaw": "`channel` {Object}", "type": "Object", "name": "channel", "meta": { "added": [ "v7.1.0" ], "changes": [] }, "desc": "

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

" }, { "textRaw": "`config` {Object}", "type": "Object", "name": "config", "meta": { "added": [ "v0.7.7" ], "changes": [] }, "desc": "

The process.config property returns an Object containing the JavaScript\nrepresentation of the configure options used to compile the current Node.js\nexecutable. This is the same as the config.gypi file that was produced when\nrunning the ./configure script.

\n

An example of the possible output looks like:

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

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

" }, { "textRaw": "`connected` {boolean}", "type": "boolean", "name": "connected", "meta": { "added": [ "v0.7.2" ], "changes": [] }, "desc": "

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

\n

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

" }, { "textRaw": "`debugPort` {number}", "type": "number", "name": "debugPort", "meta": { "added": [ "v0.7.2" ], "changes": [] }, "desc": "

The port used by Node.js's debugger when enabled.

\n
process.debugPort = 5858;\n
" }, { "textRaw": "`env` {Object}", "type": "Object", "name": "env", "meta": { "added": [ "v0.1.27" ], "changes": [ { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/18990", "description": "Implicit conversion of variable value to string is deprecated." } ] }, "desc": "

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

\n

An example of this object looks like:

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

It is possible to modify this object, but such modifications will not be\nreflected outside the Node.js process. In other words, the following example\nwould not work:

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

While the following will:

\n
process.env.foo = 'bar';\nconsole.log(process.env.foo);\n
\n

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

\n
process.env.test = null;\nconsole.log(process.env.test);\n// => 'null'\nprocess.env.test = undefined;\nconsole.log(process.env.test);\n// => 'undefined'\n
\n

Use delete to delete a property from process.env.

\n
process.env.TEST = 1;\ndelete process.env.TEST;\nconsole.log(process.env.TEST);\n// => undefined\n
\n

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

\n
process.env.TEST = 1;\nconsole.log(process.env.test);\n// => 1\n
\n

process.env is read-only in Worker threads.

" }, { "textRaw": "`execArgv` {string[]}", "type": "string[]", "name": "execArgv", "meta": { "added": [ "v0.7.7" ], "changes": [] }, "desc": "

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

\n
$ node --harmony script.js --version\n
\n

Results in process.execArgv:

\n\n
['--harmony']\n
\n

And process.argv:

\n\n
['/usr/local/bin/node', 'script.js', '--version']\n
" }, { "textRaw": "`execPath` {string}", "type": "string", "name": "execPath", "meta": { "added": [ "v0.1.100" ], "changes": [] }, "desc": "

The process.execPath property returns the absolute pathname of the executable\nthat started the Node.js process.

\n\n
'/usr/local/bin/node'\n
" }, { "textRaw": "`exitCode` {integer}", "type": "integer", "name": "exitCode", "meta": { "added": [ "v0.11.8" ], "changes": [] }, "desc": "

A number which will be the process exit code, when the process either\nexits gracefully, or is exited via process.exit() without specifying\na code.

\n

Specifying a code to process.exit(code) will override any\nprevious setting of process.exitCode.

" }, { "textRaw": "`mainModule` {Object}", "type": "Object", "name": "mainModule", "meta": { "added": [ "v0.1.17" ], "changes": [] }, "desc": "

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

\n

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

" }, { "textRaw": "`noDeprecation` {boolean}", "type": "boolean", "name": "noDeprecation", "meta": { "added": [ "v0.8.0" ], "changes": [] }, "desc": "

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

" }, { "textRaw": "`pid` {integer}", "type": "integer", "name": "pid", "meta": { "added": [ "v0.1.15" ], "changes": [] }, "desc": "

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

\n
console.log(`This process is pid ${process.pid}`);\n
" }, { "textRaw": "`platform` {string}", "type": "string", "name": "platform", "meta": { "added": [ "v0.1.16" ], "changes": [] }, "desc": "

The process.platform property returns a string identifying the operating\nsystem platform on which the Node.js process is running.

\n

Currently possible values are:

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

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

" }, { "textRaw": "`ppid` {integer}", "type": "integer", "name": "ppid", "meta": { "added": [ "v9.2.0" ], "changes": [] }, "desc": "

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

\n
console.log(`The parent process is pid ${process.ppid}`);\n
" }, { "textRaw": "`release` {Object}", "type": "Object", "name": "release", "meta": { "added": [ "v3.0.0" ], "changes": [ { "version": "v4.2.0", "pr-url": "https://github.com/nodejs/node/pull/3212", "description": "The `lts` property is now supported." } ] }, "desc": "

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

\n

process.release contains the following properties:

\n\n\n
{\n  name: 'node',\n  lts: 'Argon',\n  sourceUrl: 'https://nodejs.org/download/release/v4.4.5/node-v4.4.5.tar.gz',\n  headersUrl: 'https://nodejs.org/download/release/v4.4.5/node-v4.4.5-headers.tar.gz',\n  libUrl: 'https://nodejs.org/download/release/v4.4.5/win-x64/node.lib'\n}\n
\n

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

" }, { "textRaw": "`stderr` {Stream}", "type": "Stream", "name": "stderr", "desc": "

The process.stderr property returns a stream connected to\nstderr (fd 2). It is a net.Socket (which is a Duplex\nstream) unless fd 2 refers to a file, in which case it is\na Writable stream.

\n

process.stderr differs from other Node.js streams in important ways. See\nnote on process I/O for more information.

" }, { "textRaw": "`stdin` {Stream}", "type": "Stream", "name": "stdin", "desc": "

The process.stdin property returns a stream connected to\nstdin (fd 0). It is a net.Socket (which is a Duplex\nstream) unless fd 0 refers to a file, in which case it is\na Readable stream.

\n
process.stdin.setEncoding('utf8');\n\nprocess.stdin.on('readable', () => {\n  let chunk;\n  // Use a loop to make sure we read all available data.\n  while ((chunk = process.stdin.read()) !== null) {\n    process.stdout.write(`data: ${chunk}`);\n  }\n});\n\nprocess.stdin.on('end', () => {\n  process.stdout.write('end');\n});\n
\n

As a Duplex stream, process.stdin can also be used in \"old\" mode that\nis compatible with scripts written for Node.js prior to v0.10.\nFor more information see Stream compatibility.

\n

In \"old\" streams mode the stdin stream is paused by default, so one\nmust call process.stdin.resume() to read from it. Note also that calling\nprocess.stdin.resume() itself would switch stream to \"old\" mode.

" }, { "textRaw": "`stdout` {Stream}", "type": "Stream", "name": "stdout", "desc": "

The process.stdout property returns a stream connected to\nstdout (fd 1). It is a net.Socket (which is a Duplex\nstream) unless fd 1 refers to a file, in which case it is\na Writable stream.

\n

For example, to copy process.stdin to process.stdout:

\n
process.stdin.pipe(process.stdout);\n
\n

process.stdout differs from other Node.js streams in important ways. See\nnote on process I/O for more information.

", "modules": [ { "textRaw": "A note on process I/O", "name": "a_note_on_process_i/o", "desc": "

process.stdout and process.stderr differ from other Node.js streams in\nimportant ways:

\n
    \n
  1. They are used internally by console.log() and console.error(),\nrespectively.
  2. \n
  3. \n

    Writes may be synchronous depending on what the stream is connected to\nand whether the system is Windows or POSIX:

    \n\n
  4. \n
\n

These behaviors are partly for historical reasons, as changing them would\ncreate backwards incompatibility, but they are also expected by some users.

\n

Synchronous writes avoid problems such as output written with console.log() or\nconsole.error() being unexpectedly interleaved, or not written at all if\nprocess.exit() is called before an asynchronous write completes. See\nprocess.exit() for more information.

\n

Warning: Synchronous writes block the event loop until the write has\ncompleted. This can be near instantaneous in the case of output to a file, but\nunder high system load, pipes that are not being read at the receiving end, or\nwith slow terminals or file systems, its possible for the event loop to be\nblocked often enough and long enough to have severe negative performance\nimpacts. This may not be a problem when writing to an interactive terminal\nsession, but consider this particularly careful when doing production logging to\nthe process output streams.

\n

To check if a stream is connected to a TTY context, check the isTTY\nproperty.

\n

For instance:

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

See the TTY documentation for more information.

", "type": "module", "displayName": "A note on process I/O" } ] }, { "textRaw": "`throwDeprecation` {boolean}", "type": "boolean", "name": "throwDeprecation", "meta": { "added": [ "v0.9.12" ], "changes": [] }, "desc": "

The process.throwDeprecation property indicates whether the\n--throw-deprecation flag is set on the current Node.js process. See the\ndocumentation for the 'warning' event and the\nemitWarning() method for more information about this\nflag's behavior.

" }, { "textRaw": "`title` {string}", "type": "string", "name": "title", "meta": { "added": [ "v0.1.104" ], "changes": [] }, "desc": "

The process.title property returns the current process title (i.e. returns\nthe current value of ps). Assigning a new value to process.title modifies\nthe current value of ps.

\n

When a new value is assigned, different platforms will impose different maximum\nlength restrictions on the title. Usually such restrictions are quite limited.\nFor instance, on Linux and macOS, process.title is limited to the size of the\nbinary name plus the length of the command line arguments because setting the\nprocess.title overwrites the argv memory of the process. Node.js v0.8\nallowed for longer process title strings by also overwriting the environ\nmemory but that was potentially insecure and confusing in some (rather obscure)\ncases.

" }, { "textRaw": "`traceDeprecation` {boolean}", "type": "boolean", "name": "traceDeprecation", "meta": { "added": [ "v0.8.0" ], "changes": [] }, "desc": "

The process.traceDeprecation property indicates whether the\n--trace-deprecation flag is set on the current Node.js process. See the\ndocumentation for the 'warning' event and the\nemitWarning() method for more information about this\nflag's behavior.

" }, { "textRaw": "`version` {string}", "type": "string", "name": "version", "meta": { "added": [ "v0.1.3" ], "changes": [] }, "desc": "

The process.version property returns the Node.js version string.

\n
console.log(`Version: ${process.version}`);\n
" }, { "textRaw": "`versions` {Object}", "type": "Object", "name": "versions", "meta": { "added": [ "v0.2.0" ], "changes": [ { "version": "v4.2.0", "pr-url": "https://github.com/nodejs/node/pull/3102", "description": "The `icu` property is now supported." }, { "version": "v9.0.0", "pr-url": "https://github.com/nodejs/node/pull/15785", "description": "The `v8` property now includes a Node.js specific suffix." } ] }, "desc": "

The process.versions property returns an object listing the version strings of\nNode.js and its dependencies. process.versions.modules indicates the current\nABI version, which is increased whenever a C++ API changes. Node.js will refuse\nto load modules that were compiled against a different module ABI version.

\n
console.log(process.versions);\n
\n

Will generate an object similar to:

\n\n
{ http_parser: '2.7.0',\n  node: '8.9.0',\n  v8: '6.3.292.48-node.6',\n  uv: '1.18.0',\n  zlib: '1.2.11',\n  ares: '1.13.0',\n  modules: '60',\n  nghttp2: '1.29.0',\n  napi: '2',\n  openssl: '1.0.2n',\n  icu: '60.1',\n  unicode: '10.0',\n  cldr: '32.0',\n  tz: '2016b' }\n
" } ] } ] }