{ "source": "doc/api/process.md", "globals": [ { "textRaw": "process", "name": "process", "type": "global", "desc": "

The process object is a global object and can be accessed from anywhere.\nIt is an instance of [EventEmitter][].

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

This event is emitted when Node.js empties its event loop and has nothing else\nto schedule. Normally, Node.js exits when there is no work scheduled, but a\nlistener for 'beforeExit' can make asynchronous calls, and cause Node.js to\ncontinue.

\n

'beforeExit' is not emitted for conditions causing explicit termination, such\nas [process.exit()][] or uncaught exceptions, and should not be used as an\nalternative to the 'exit' event unless the intention is to schedule more work.

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

If process is spawned with an IPC channel, 'disconnect' will be emitted when\nIPC channel is closed. Read more in [child_process 'disconnect' event][] doc.

\n", "params": [] }, { "textRaw": "Event: 'exit'", "type": "event", "name": "exit", "meta": { "added": [ "v0.1.7" ] }, "desc": "

Emitted when the process is about to exit. There is no way to prevent the\nexiting of the event loop at this point, and once all 'exit' listeners have\nfinished running the process will exit. Therefore you must only perform\nsynchronous operations in this handler. This is a good hook to perform\nchecks on the module's state (like for unit tests). The callback takes one\nargument, the code the process is exiting with.

\n

This event is only emitted when Node.js exits explicitly by process.exit() or\nimplicitly by the event loop draining.

\n

Example of listening for 'exit':

\n
process.on('exit', (code) => {\n  // do *NOT* do this\n  setTimeout(() => {\n    console.log('This will not run');\n  }, 0);\n  console.log('About to exit with code:', code);\n});\n
\n", "params": [] }, { "textRaw": "Event: 'message'", "type": "event", "name": "message", "meta": { "added": [ "v0.5.10" ] }, "params": [], "desc": "

Messages sent by [ChildProcess.send()][] are obtained using the 'message'\nevent on the child's process object.

\n" }, { "textRaw": "Event: 'rejectionHandled'", "type": "event", "name": "rejectionHandled", "meta": { "added": [ "v1.4.1" ] }, "desc": "

Emitted whenever a Promise was rejected and an error handler was attached to it\n(for example with [promise.catch()][]) later than after an event loop turn. This event\nis emitted with the following arguments:

\n\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 rejection\ncan be handled at a future point in time — possibly much later than the\nevent 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 is a\ngrowing-and-shrinking list of unhandled rejections. In synchronous code, the\n'uncaughtException' event tells you when the list of unhandled exceptions\ngrows. And in asynchronous code, the 'unhandledRejection' event tells you\nwhen the list of unhandled rejections grows, while the 'rejectionHandled'\nevent tells you when the list of unhandled rejections shrinks.

\n

For example using the rejection detection hooks in order to keep a map of all\nthe rejected promise reasons at a given time:

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

This map will grow and shrink over time, reflecting rejections that start\nunhandled and then become handled. You could record the errors in some error\nlog, either periodically (probably best for long-running programs, allowing\nyou to clear the map, which in the case of a very buggy program could grow\nindefinitely) or upon process exit (more convenient for scripts).

\n", "params": [] }, { "textRaw": "Event: 'uncaughtException'", "type": "event", "name": "uncaughtException", "meta": { "added": [ "v0.1.18" ] }, "desc": "

The 'uncaughtException' event is emitted when an exception bubbles all the\nway back to the event loop. By default, Node.js handles such exceptions by\nprinting the stack trace to stderr and exiting. Adding a handler for the\n'uncaughtException' event overrides this default behavior.

\n

For example:

\n
process.on('uncaughtException', (err) => {\n  console.log(`Caught exception: ${err}`);\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
\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", "type": "module", "displayName": "Warning: Using `'uncaughtException'` correctly" } ], "params": [] }, { "textRaw": "Event: 'unhandledRejection'", "type": "event", "name": "unhandledRejection", "meta": { "added": [ "v1.4.1" ] }, "desc": "

Emitted whenever a Promise is rejected and no error handler is attached to\nthe promise within a turn of the event loop. When programming with promises\nexceptions are encapsulated as rejected promises. Such promises can be caught\nand handled using [promise.catch()][] and rejections are propagated through\na promise chain. This event is useful for detecting and keeping track of\npromises that were rejected whose rejections were not handled yet. This event\nis emitted with the following arguments:

\n\n

Here is an example that logs every unhandled rejection to the console

\n
process.on('unhandledRejection', (reason, p) => {\n    console.log("Unhandled Rejection at: Promise ", p, " reason: ", reason);\n    // application specific logging, throwing an error, or other logic here\n});\n
\n

For example, here is a rejection that will trigger the 'unhandledRejection'\nevent:

\n
somePromise.then((res) => {\n  return reportToUser(JSON.pasre(res)); // note the typo (`pasre`)\n}); // no `.catch` or `.then`\n
\n

Here is an example of a coding pattern that will also trigger\n'unhandledRejection':

\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\nvar resource = new SomeResource();\n// no .catch or .then on resource.loaded for at least a turn\n
\n

In cases like this, you may not want to track the rejection as a developer\nerror like you would for other 'unhandledRejection' events. To address\nthis, you can either attach a dummy [.catch(() => { })][promise.catch()] handler to\nresource.loaded, preventing the 'unhandledRejection' event from being\nemitted, or you can use the ['rejectionHandled'][] event.

\n", "params": [] }, { "textRaw": "Event: 'warning'", "type": "event", "name": "warning", "meta": { "added": [ "v6.0.0" ] }, "desc": "

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

The event handler for 'warning' events is called with a single warning\nargument whose value is an Error object. There are three key properties that\ndescribe the warning:

\n\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> event.defaultMaxListeners = 1;\n> process.on('foo', () => {});\n> process.on('foo', () => {});\n> (node:38638) Warning: Possible EventEmitter memory leak detected. 2 foo\n... listeners added. Use emitter.setMaxListeners() to increase limit\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> var p = process.on('warning', (warning) => console.warn('Do not do that!'));\n> event.defaultMaxListeners = 1;\n> process.on('foo', () => {});\n> process.on('foo', () => {});\n> Do not do that!\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", "modules": [ { "textRaw": "Emitting custom warnings", "name": "emitting_custom_warnings", "desc": "

The [process.emitWarning()][process_emit_warning] method can be used to issue\ncustom or application specific warnings.

\n
// Emit a warning using a string...\nprocess.emitWarning('Something happened!');\n  // Prints: (node 12345) Warning: Something happened!\n\n// Emit a warning using an object...\nprocess.emitWarning('Something Happened!', 'CustomWarning');\n  // Prints: (node 12345) CustomWarning: Something happened!\n\n// Emit a warning using a custom Error object...\nclass CustomWarning extends Error {\n  constructor(message) {\n    super(message);\n    this.name = 'CustomWarning';\n    Error.captureStackTrace(this, CustomWarning);\n  }\n}\nconst myWarning = new CustomWarning('Something happened!');\nprocess.emitWarning(myWarning);\n  // Prints: (node 12345) CustomWarning: Something happened!\n
\n", "type": "module", "displayName": "Emitting custom warnings" }, { "textRaw": "Emitting custom deprecation warnings", "name": "emitting_custom_deprecation_warnings", "desc": "

Custom deprecation warnings can be emitted by setting the name of a custom\nwarning to DeprecationWarning. For instance:

\n
process.emitWarning('This API is deprecated', 'DeprecationWarning');\n
\n

Or,

\n
const err = new Error('This API is deprecated');\nerr.name = 'DeprecationWarning';\nprocess.emitWarning(err);\n
\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\nDeprecationWarning.

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

Emitted when the processes receives a signal. See sigaction(2) for a list of\nstandard POSIX signal names such as SIGINT, SIGHUP, etc.

\n

Example of listening for SIGINT:

\n
// Start reading from stdin so we don't exit.\nprocess.stdin.resume();\n\nprocess.on('SIGINT', () => {\n  console.log('Got SIGINT.  Press Control-D to exit.');\n});\n
\n

An easy way to send the SIGINT signal is with Control-C in most terminal\nprograms.

\n

Note:

\n\n

Note that Windows does not support sending Signals, but Node.js offers some\nemulation with [process.kill()][], and [ChildProcess.kill()][]. Sending signal 0\ncan be used to test for the existence of a process. Sending SIGINT,\nSIGTERM, and SIGKILL cause the unconditional termination of the target\nprocess.

\n", "params": [] } ], "modules": [ { "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\n", "type": "module", "displayName": "Exit Codes" } ], "methods": [ { "textRaw": "process.abort()", "type": "method", "name": "abort", "meta": { "added": [ "v0.7.0" ] }, "desc": "

This causes Node.js to emit an abort. This will cause Node.js to exit and\ngenerate a core file.

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

Changes the current working directory of the process or throws an exception if that fails.

\n
console.log(`Starting directory: ${process.cwd()}`);\ntry {\n  process.chdir('/tmp');\n  console.log(`New directory: ${process.cwd()}`);\n}\ncatch (err) {\n  console.log(`chdir: ${err}`);\n}\n
\n", "signatures": [ { "params": [ { "name": "directory" } ] } ] }, { "textRaw": "process.cpuUsage([previousValue])", "type": "method", "name": "cpuUsage", "desc": "\n

Returns the user and system CPU time usage of the current process, in an object\nwith properties user and system, whose values are microsecond values\n(millionth of a second). These values measure time spent in user and\nsystem code respectively, and may end up being greater than actual elapsed time\nif 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
\n", "signatures": [ { "params": [ { "name": "previousValue", "optional": true } ] } ] }, { "textRaw": "process.cwd()", "type": "method", "name": "cwd", "meta": { "added": [ "v0.1.8" ] }, "desc": "

Returns the current working directory of the process.

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

Close the IPC channel to the parent process, allowing this child to exit\ngracefully once there are no other connections keeping it alive.

\n

Identical to the parent process's [ChildProcess.disconnect()][].

\n

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

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "process.emitWarning(warning[, name][, ctor])", "type": "method", "name": "emitWarning", "meta": { "added": [ "v6.0.0" ] }, "signatures": [ { "params": [ { "textRaw": "`warning` {String | Error} The warning to emit. ", "name": "warning", "type": "String | Error", "desc": "The warning to emit." }, { "textRaw": "`name` {String} When `warning` is a String, `name` is the name to use for the warning. Default: `Warning`. ", "name": "name", "type": "String", "desc": "When `warning` is a String, `name` is the name to use for the warning. Default: `Warning`.", "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", "desc": "When `warning` is a String, `ctor` is an optional function used to limit the generated stack trace. Default `process.emitWarning`", "optional": true } ] }, { "params": [ { "name": "warning" }, { "name": "name", "optional": true }, { "name": "ctor", "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[process.on('warning')][process_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 name...\nprocess.emitWarning('Something Happened!', 'CustomWarning');\n  // Emits: (node:56338) CustomWarning: Something Happened!\n

In each of the previous examples, an Error object is generated internally by\nprocess.emitWarning() and passed through to the\n[process.on('warning')][process_warning] event.

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

If warning is passed as an Error object, it will be passed through to the\nprocess.on('warning') event handler unmodified (and the optional name\nand ctor arguments will be ignored):

\n
// Emit a warning using an Error object...\nconst myWarning = new Error('Warning! Something happened!');\nmyWarning.name = 'CustomWarning';\n\nprocess.emitWarning(myWarning);\n  // Emits: (node:56338) CustomWarning: Warning! Something Happened!\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 name is\nDeprecationWarning:

\n\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
var warned = false;\nfunction emitMyWarning() {\n  if (!warned) {\n    process.emitWarning('Only warn once!');\n    warned = true;\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" ] }, "signatures": [ { "params": [ { "textRaw": "`code` {Integer} The exit code. Defaults to `0`. ", "name": "code", "type": "Integer", "desc": "The exit code. Defaults to `0`.", "optional": true } ] }, { "params": [ { "name": "code", "optional": true } ] } ], "desc": "

The process.exit() method instructs Node.js to terminate the process as\nquickly as possible with the specified exit code. If the code is omitted, \nexit uses either the 'success' code 0 or the value of process.exitCode if\nspecified.

\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

It is important to note that calling process.exit() will force the process to\nexit as quickly as possible even if there are still asynchronous operations \npending that have not yet completed fully, including I/O operations to\nprocess.stdout and process.stderr.

\n

In most situations, it is not actually necessary to call process.exit()\nexplicitly. The Node.js process will exit on it's 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 non-blocking and may occur over multiple ticks of the Node.js event loop.\nCalling process.exit(), however, forces the process to exit before those\nadditional 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" }, { "textRaw": "process.getegid()", "type": "method", "name": "getegid", "meta": { "added": [ "v2.0.0" ] }, "desc": "

Note: this function is only available on POSIX platforms (i.e. not Windows,\nAndroid)

\n

Gets the effective group identity of the process. (See getegid(2).)\nThis is the numerical group id, not the group name.

\n
if (process.getegid) {\n  console.log(`Current gid: ${process.getegid()}`);\n}\n
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "process.geteuid()", "type": "method", "name": "geteuid", "meta": { "added": [ "v2.0.0" ] }, "desc": "

Note: this function is only available on POSIX platforms (i.e. not Windows,\nAndroid)

\n

Gets the effective user identity of the process. (See geteuid(2).)\nThis is the numerical userid, not the username.

\n
if (process.geteuid) {\n  console.log(`Current uid: ${process.geteuid()}`);\n}\n
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "process.getgid()", "type": "method", "name": "getgid", "meta": { "added": [ "v0.1.31" ] }, "desc": "

Note: this function is only available on POSIX platforms (i.e. not Windows,\nAndroid)

\n

Gets the group identity of the process. (See getgid(2).)\nThis is the numerical group id, not the group name.

\n
if (process.getgid) {\n  console.log(`Current gid: ${process.getgid()}`);\n}\n
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "process.getgroups()", "type": "method", "name": "getgroups", "meta": { "added": [ "v0.9.4" ] }, "desc": "

Note: this function is only available on POSIX platforms (i.e. not Windows,\nAndroid)

\n

Returns an array with the supplementary group IDs. POSIX leaves it unspecified\nif the effective group ID is included but Node.js ensures it always is.

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "process.getuid()", "type": "method", "name": "getuid", "meta": { "added": [ "v0.1.28" ] }, "desc": "

Note: this function is only available on POSIX platforms (i.e. not Windows,\nAndroid)

\n

Gets the user identity of the process. (See getuid(2).)\nThis is the numerical userid, not the username.

\n
if (process.getuid) {\n  console.log(`Current uid: ${process.getuid()}`);\n}\n
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "process.hrtime()", "type": "method", "name": "hrtime", "meta": { "added": [ "v0.7.6" ] }, "desc": "

Returns the current high-resolution real time in a [seconds, nanoseconds]\ntuple Array. It is relative to an arbitrary time in the past. It is not\nrelated to the time of day and therefore not subject to clock drift. The\nprimary use is for measuring performance between intervals.

\n

You may pass in the result of a previous call to process.hrtime() to get\na diff reading, useful for benchmarks and measuring intervals:

\n
var time = process.hrtime();\n// [ 1800216, 25 ]\n\nsetTimeout(() => {\n  var diff = process.hrtime(time);\n  // [ 1, 552 ]\n\n  console.log('benchmark took %d nanoseconds', diff[0] * 1e9 + diff[1]);\n  // benchmark took 1000000527 nanoseconds\n}, 1000);\n
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "process.initgroups(user, extra_group)", "type": "method", "name": "initgroups", "meta": { "added": [ "v0.9.4" ] }, "desc": "

Note: this function is only available on POSIX platforms (i.e. not Windows,\nAndroid)

\n

Reads /etc/group and initializes the group access list, using all groups of\nwhich the user is a member. This is a privileged operation, meaning you need\nto be root or have the CAP_SETGID capability.

\n

user is a user name or user ID. extra_group is a group name or group ID.

\n

Some care needs to be taken when dropping privileges. Example:

\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", "signatures": [ { "params": [ { "name": "user" }, { "name": "extra_group" } ] } ] }, { "textRaw": "process.kill(pid[, signal])", "type": "method", "name": "kill", "meta": { "added": [ "v0.0.6" ] }, "desc": "

Send a signal to a process. pid is the process id and signal is the\nstring describing the signal to send. Signal names are strings like\n'SIGINT' or 'SIGHUP'. If omitted, the signal will be 'SIGTERM'.\nSee [Signal Events][] and kill(2) for more information.

\n

Will throw an error if target does not exist, and as a special case, a signal\nof 0 can be used to test for the existence of a process. Windows platforms\nwill throw an error if the pid is used to kill a process group.

\n

Note that even though the name of this function is process.kill, it is really\njust a signal sender, like the kill system call. The signal sent may do\nsomething other than kill the target process.

\n

Example of sending a signal to yourself:

\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

Note: When SIGUSR1 is received by Node.js it starts the debugger, see\n[Signal Events][].

\n", "signatures": [ { "params": [ { "name": "pid" }, { "name": "signal", "optional": true } ] } ] }, { "textRaw": "process.memoryUsage()", "type": "method", "name": "memoryUsage", "meta": { "added": [ "v0.1.16" ] }, "desc": "

Returns an object describing the memory usage of the Node.js process\nmeasured in bytes.

\n
const util = require('util');\n\nconsole.log(util.inspect(process.memoryUsage()));\n
\n

This will generate:

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

heapTotal and heapUsed refer to V8's memory usage.

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "process.nextTick(callback[, arg][, ...])", "type": "method", "name": "nextTick", "meta": { "added": [ "v0.1.26" ] }, "signatures": [ { "params": [ { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function" }, { "name": "arg", "optional": true }, { "name": "...", "optional": true } ] }, { "params": [ { "name": "callback" }, { "name": "arg", "optional": true }, { "name": "...", "optional": true } ] } ], "desc": "

Once the current event loop turn runs to completion, call the callback\nfunction.

\n

This is not a simple alias to [setTimeout(fn, 0)][], it's 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 in developing APIs where you want to give the user the\nchance to assign event handlers after an object has been constructed,\nbut before any I/O has occurred.

\n
function MyThing(options) {\n  this.setupOptions(options);\n\n  process.nextTick(() => {\n    this.startDoingStuff();\n  });\n}\n\nvar 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. If you do this:

\n
maybeSync(true, () => {\n  foo();\n});\nbar();\n
\n

then it's not clear whether foo() or bar() will be called first.

\n

This 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

Note: the nextTick queue is completely drained on each pass of the\nevent loop before additional I/O is processed. As a result,\nrecursively setting nextTick callbacks will block any I/O from\nhappening, just like a while(true); loop.

\n" }, { "textRaw": "process.send(message[, sendHandle[, options]][, callback])", "type": "method", "name": "send", "meta": { "added": [ "v0.5.9" ] }, "signatures": [ { "return": { "textRaw": "Return: {Boolean} ", "name": "return", "type": "Boolean" }, "params": [ { "textRaw": "`message` {Object} ", "name": "message", "type": "Object" }, { "textRaw": "`sendHandle` {Handle object} ", "name": "sendHandle", "type": "Handle object", "optional": true }, { "textRaw": "`options` {Object} ", "name": "options", "type": "Object", "optional": true }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function", "optional": true } ] }, { "params": [ { "name": "message" }, { "name": "sendHandle", "optional": true }, { "name": "options", "optional": true }, { "name": "callback", "optional": true } ] } ], "desc": "

When Node.js is spawned with an IPC channel attached, it can send messages to its\nparent process using process.send(). Each will be received as a\n['message'][] event on the parent's [ChildProcess][] object.

\n

Note: this function uses [JSON.stringify()][] internally to serialize the message.

\n

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

\n" }, { "textRaw": "process.setegid(id)", "type": "method", "name": "setegid", "meta": { "added": [ "v2.0.0" ] }, "desc": "

Note: this function is only available on POSIX platforms (i.e. not Windows,\nAndroid)

\n

Sets the effective group identity of the process. (See setegid(2).)\nThis accepts either a numerical ID or a group name string. If a group name\nis specified, this method blocks while resolving it to a numerical 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  }\n  catch (err) {\n    console.log(`Failed to set gid: ${err}`);\n  }\n}\n
\n", "signatures": [ { "params": [ { "name": "id" } ] } ] }, { "textRaw": "process.seteuid(id)", "type": "method", "name": "seteuid", "meta": { "added": [ "v2.0.0" ] }, "desc": "

Note: this function is only available on POSIX platforms (i.e. not Windows,\nAndroid)

\n

Sets the effective user identity of the process. (See seteuid(2).)\nThis accepts either a numerical ID or a username string. If a username\nis specified, this method blocks while resolving it to a numerical 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  }\n  catch (err) {\n    console.log(`Failed to set uid: ${err}`);\n  }\n}\n
\n", "signatures": [ { "params": [ { "name": "id" } ] } ] }, { "textRaw": "process.setgid(id)", "type": "method", "name": "setgid", "meta": { "added": [ "v0.1.31" ] }, "desc": "

Note: this function is only available on POSIX platforms (i.e. not Windows,\nAndroid)

\n

Sets the group identity of the process. (See setgid(2).) This accepts either\na numerical ID or a group name string. If a group name is specified, this method\nblocks while resolving it to a numerical 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  }\n  catch (err) {\n    console.log(`Failed to set gid: ${err}`);\n  }\n}\n
\n", "signatures": [ { "params": [ { "name": "id" } ] } ] }, { "textRaw": "process.setgroups(groups)", "type": "method", "name": "setgroups", "meta": { "added": [ "v0.9.4" ] }, "desc": "

Note: this function is only available on POSIX platforms (i.e. not Windows,\nAndroid)

\n

Sets the supplementary group IDs. This is a privileged operation, meaning you\nneed to be root or have the CAP_SETGID capability.

\n

The list can contain group IDs, group names or both.

\n", "signatures": [ { "params": [ { "name": "groups" } ] } ] }, { "textRaw": "process.setuid(id)", "type": "method", "name": "setuid", "meta": { "added": [ "v0.1.28" ] }, "desc": "

Note: this function is only available on POSIX platforms (i.e. not Windows,\nAndroid)

\n

Sets the user identity of the process. (See setuid(2).) This accepts either\na numerical ID or a username string. If a username is specified, this method\nblocks while resolving it to a numerical 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  }\n  catch (err) {\n    console.log(`Failed to set uid: ${err}`);\n  }\n}\n
\n", "signatures": [ { "params": [ { "name": "id" } ] } ] }, { "textRaw": "process.umask([mask])", "type": "method", "name": "umask", "meta": { "added": [ "v0.1.19" ] }, "desc": "

Sets or reads the process's file mode creation mask. Child processes inherit\nthe mask from the parent process. Returns the old mask if mask argument is\ngiven, otherwise returns the current mask.

\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", "signatures": [ { "params": [ { "name": "mask", "optional": true } ] } ] }, { "textRaw": "process.uptime()", "type": "method", "name": "uptime", "meta": { "added": [ "v0.5.0" ] }, "desc": "

Number of seconds Node.js has been running.

\n", "signatures": [ { "params": [] } ] } ], "properties": [ { "textRaw": "process.arch", "name": "arch", "meta": { "added": [ "v0.5.0" ] }, "desc": "

What processor architecture you're running on: 'arm', 'ia32', or 'x64'.

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

An array containing the command line arguments. The first element will be\n'node', the second element will be the name of the JavaScript file. The\nnext elements will be any additional command line arguments.

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

This will generate:

\n
$ node process-2.js one two=three four\n0: node\n1: /Users/mjr/work/node/process-2.js\n2: one\n3: two=three\n4: four\n
" }, { "textRaw": "process.config", "name": "config", "meta": { "added": [ "v0.7.7" ] }, "desc": "

An Object containing the JavaScript representation of the configure options\nthat were used to compile the current Node.js executable. This is the same as\nthe config.gypi file that was produced when running the ./configure script.

\n

An example of the possible output looks like:

\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

Note: 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.

\n" }, { "textRaw": "`connected` {Boolean} Set to `false` after `process.disconnect()` is called ", "type": "Boolean", "name": "connected", "meta": { "added": [ "v0.7.2" ] }, "desc": "

If process.connected is false, it is no longer possible to send messages.

\n", "shortDesc": "Set to `false` after `process.disconnect()` is called" }, { "textRaw": "process.env", "name": "env", "meta": { "added": [ "v0.1.27" ] }, "desc": "

An object containing the user environment. See environ(7).

\n

An example of this object looks like:

\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

You can write to this object, but changes won't be reflected outside of your\nprocess. That means that the following won't work:

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

But this 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.

\n

Example:

\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

Example:

\n
process.env.TEST = 1;\ndelete process.env.TEST;\nconsole.log(process.env.TEST);\n// => undefined\n
\n" }, { "textRaw": "process.execArgv", "name": "execArgv", "meta": { "added": [ "v0.7.7" ] }, "desc": "

This is the set of Node.js-specific command line options from the\nexecutable that started the process. These options do not show up in\n[process.argv][], and do not include the Node.js executable, the name of\nthe script, or any options following the script name. These options\nare useful in order to spawn child processes with the same execution\nenvironment as the parent.

\n

Example:

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

results in process.execArgv:

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

and process.argv:

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

This is the absolute pathname of the executable that started the process.

\n

Example:

\n
/usr/local/bin/node\n
" }, { "textRaw": "process.exitCode", "name": "exitCode", "meta": { "added": [ "v0.11.8" ] }, "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)][process.exit()] will override any \nprevious setting of process.exitCode.

\n" }, { "textRaw": "process.mainModule", "name": "mainModule", "meta": { "added": [ "v0.1.17" ] }, "desc": "

Alternate way to retrieve [require.main][]. The difference is that if the main\nmodule changes at runtime, [require.main][] might still refer to the original main\nmodule in modules 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][], it will be undefined if there was no entry script.

\n" }, { "textRaw": "process.pid", "name": "pid", "meta": { "added": [ "v0.1.15" ] }, "desc": "

The PID of the process.

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

What platform you're running on:\n'darwin', 'freebsd', 'linux', 'sunos' or 'win32'

\n
console.log(`This platform is ${process.platform}`);\n
\n" }, { "textRaw": "process.release", "name": "release", "meta": { "added": [ "v3.0.0" ] }, "desc": "

An Object containing metadata related to the current release, including URLs\nfor the source tarball and headers-only tarball.

\n

process.release contains the following properties:

\n\n

e.g.

\n
{ name: 'node',\n  sourceUrl: 'https://nodejs.org/download/release/v4.0.0/node-v4.0.0.tar.gz',\n  headersUrl: 'https://nodejs.org/download/release/v4.0.0/node-v4.0.0-headers.tar.gz',\n  libUrl: 'https://nodejs.org/download/release/v4.0.0/win-x64/node.lib' }\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.

\n" }, { "textRaw": "process.stderr", "name": "stderr", "desc": "

A writable stream to stderr (on fd 2).

\n

process.stderr and process.stdout are unlike other streams in Node.js in\nthat they cannot be closed ([end()][] will throw), they never emit the ['finish'][]\nevent and that writes can block when output is redirected to a file (although\ndisks are fast and operating systems normally employ write-back caching so it\nshould be a very rare occurrence indeed.)

\n" }, { "textRaw": "process.stdin", "name": "stdin", "desc": "

A Readable Stream for stdin (on fd 0).

\n

Example of opening standard input and listening for both events:

\n
process.stdin.setEncoding('utf8');\n\nprocess.stdin.on('readable', () => {\n  var chunk = process.stdin.read();\n  if (chunk !== null) {\n    process.stdout.write(`data: ${chunk}`);\n  }\n});\n\nprocess.stdin.on('end', () => {\n  process.stdout.write('end');\n});\n
\n

As a Stream, process.stdin can also be used in "old" mode that is compatible\nwith 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.

\n

If you are starting a new project you should prefer a more recent "new" Streams\nmode over "old" one.

\n" }, { "textRaw": "process.stdout", "name": "stdout", "desc": "

A Writable Stream to stdout (on fd 1).

\n

For example, a console.log equivalent could look like this:

\n
console.log = (msg) => {\n  process.stdout.write(`${msg}\\n`);\n};\n
\n

process.stderr and process.stdout are unlike other streams in Node.js in\nthat they cannot be closed ([end()][] will throw), they never emit the ['finish'][]\nevent and that writes can block when output is redirected to a file (although\ndisks are fast and operating systems normally employ write-back caching so it\nshould be a very rare occurrence indeed.)

\n

To check if Node.js is being run in a TTY context, read the isTTY property\non process.stderr, process.stdout, or process.stdin:

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

See [the tty docs][] for more information.

\n" }, { "textRaw": "process.title", "name": "title", "meta": { "added": [ "v0.1.104" ] }, "desc": "

Getter/setter to set what is displayed in ps.

\n

When used as a setter, the maximum length is platform-specific and probably\nshort.

\n

On Linux and OS X, it's limited to the size of the binary name plus the\nlength of the command line arguments because it overwrites the argv memory.

\n

v0.8 allowed for longer process title strings by also overwriting the environ\nmemory but that was potentially insecure/confusing in some (rather obscure)\ncases.

\n" }, { "textRaw": "process.version", "name": "version", "meta": { "added": [ "v0.1.3" ] }, "desc": "

A compiled-in property that exposes NODE_VERSION.

\n
console.log(`Version: ${process.version}`);\n
\n" }, { "textRaw": "process.versions", "name": "versions", "meta": { "added": [ "v0.2.0" ] }, "desc": "

A property exposing version strings of Node.js and its dependencies.

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

Will print something like:

\n
{ http_parser: '2.3.0',\n  node: '1.1.1',\n  v8: '4.1.0.14',\n  uv: '1.3.0',\n  zlib: '1.2.8',\n  ares: '1.10.0-DEV',\n  modules: '43',\n  icu: '55.1',\n  openssl: '1.0.1k' }\n
\n" } ] } ] }