Source Code: lib/process.js
The process object provides information about, and control over, the current\nNode.js process.
process
import process from 'node:process';\n
const process = require('node:process');\n
The process object is an instance of EventEmitter.
EventEmitter
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.
'beforeExit'
The listener callback function is invoked with the value of\nprocess.exitCode passed as the only argument.
process.exitCode
The 'beforeExit' event is not emitted for conditions causing explicit\ntermination, such as calling process.exit() or uncaught exceptions.
process.exit()
The 'beforeExit' should not be used as an alternative to the 'exit' event\nunless the intention is to schedule additional work.
'exit'
import process from 'node:process';\n\nprocess.on('beforeExit', (code) => {\n console.log('Process beforeExit event with code: ', code);\n});\n\nprocess.on('exit', (code) => {\n console.log('Process exit event with code: ', code);\n});\n\nconsole.log('This message is displayed first.');\n\n// Prints:\n// This message is displayed first.\n// Process beforeExit event with code: 0\n// Process exit event with code: 0\n
const process = require('node:process');\n\nprocess.on('beforeExit', (code) => {\n console.log('Process beforeExit event with code: ', code);\n});\n\nprocess.on('exit', (code) => {\n console.log('Process exit event with code: ', code);\n});\n\nconsole.log('This message is displayed first.');\n\n// Prints:\n// This message is displayed first.\n// Process beforeExit event with code: 0\n// Process exit event with code: 0\n
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.
'disconnect'
The 'exit' event is emitted when the Node.js process is about to exit as a\nresult of either:
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.
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.
exitCode
import process from 'node:process';\n\nprocess.on('exit', (code) => {\n console.log(`About to exit with code: ${code}`);\n});\n
const process = require('node:process');\n\nprocess.on('exit', (code) => {\n console.log(`About to exit with code: ${code}`);\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:
import process from 'node:process';\n\nprocess.on('exit', (code) => {\n setTimeout(() => {\n console.log('This will not run');\n }, 0);\n});\n
const process = require('node:process');\n\nprocess.on('exit', (code) => {\n setTimeout(() => {\n console.log('This will not run');\n }, 0);\n});\n
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.
'message'
childprocess.send()
The message goes through serialization and parsing. The resulting message might\nnot be the same as what is originally sent.
If the serialization option was set to advanced used when spawning the\nprocess, the message argument can contain data that JSON is not able\nto represent.\nSee Advanced serialization for child_process for more details.
serialization
advanced
message
child_process
The 'multipleResolves' event is emitted whenever a Promise has been either:
'multipleResolves'
Promise
This is useful for tracking potential errors in an application while using the\nPromise constructor, as multiple resolutions are silently swallowed. However,\nthe occurrence of this event does not necessarily indicate an error. For\nexample, Promise.race() can trigger a 'multipleResolves' event.
Promise.race()
Because of the unreliability of the event in cases like the\nPromise.race() example above it has been deprecated.
import process from 'node:process';\n\nprocess.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
const process = require('node:process');\n\nprocess.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
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.
'rejectionHandled'
promise.catch()
The Promise object would have previously been emitted in an\n'unhandledRejection' event, but during the course of processing gained a\nrejection handler.
'unhandledRejection'
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.
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.
In synchronous code, the 'uncaughtException' event is emitted when the list of\nunhandled exceptions grows.
'uncaughtException'
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.
import process from 'node:process';\n\nconst unhandledRejections = new Map();\nprocess.on('unhandledRejection', (reason, promise) => {\n unhandledRejections.set(promise, reason);\n});\nprocess.on('rejectionHandled', (promise) => {\n unhandledRejections.delete(promise);\n});\n
const process = require('node:process');\n\nconst unhandledRejections = new Map();\nprocess.on('unhandledRejection', (reason, promise) => {\n unhandledRejections.set(promise, reason);\n});\nprocess.on('rejectionHandled', (promise) => {\n unhandledRejections.delete(promise);\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).
unhandledRejections
Map
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.
stderr
import process from 'node:process';\n\nprocess.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
const process = require('node:process');\n\nprocess.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
It is possible to monitor 'uncaughtException' events without overriding the\ndefault behavior to exit the process by installing a\n'uncaughtExceptionMonitor' listener.
'uncaughtExceptionMonitor'
'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.
On Error Resume Next
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.
Attempting to resume normally after an uncaught exception can be similar to\npulling out the power cord when upgrading a computer. Nine out of ten\ntimes, nothing happens. But the tenth time, the system becomes corrupted.
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'.
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.
The 'uncaughtExceptionMonitor' event is emitted before an\n'uncaughtException' event is emitted or a hook installed via\nprocess.setUncaughtExceptionCaptureCallback() is called.
process.setUncaughtExceptionCaptureCallback()
Installing an 'uncaughtExceptionMonitor' listener does not change the behavior\nonce an 'uncaughtException' event is emitted. The process will\nstill crash if no 'uncaughtException' listener is installed.
import process from 'node:process';\n\nprocess.on('uncaughtExceptionMonitor', (err, origin) => {\n MyMonitoringTool.logSync(err, origin);\n});\n\n// Intentionally cause an exception, but don't catch it.\nnonexistentFunc();\n// Still crashes Node.js\n
const process = require('node:process');\n\nprocess.on('uncaughtExceptionMonitor', (err, origin) => {\n MyMonitoringTool.logSync(err, origin);\n});\n\n// Intentionally cause an exception, but don't catch it.\nnonexistentFunc();\n// Still crashes Node.js\n
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.
import process from 'node:process';\n\nprocess.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
const process = require('node:process');\n\nprocess.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
The following will also trigger the 'unhandledRejection' event to be\nemitted:
import process from 'node:process';\n\nfunction 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
const process = require('node:process');\n\nfunction 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
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.
.catch(() => { })
resource.loaded
The 'warning' event is emitted whenever Node.js emits a process warning.
'warning'
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.
import process from 'node:process';\n\nprocess.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
const process = require('node:process');\n\nprocess.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
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.
--no-warnings
The following example illustrates the warning that is printed to stderr when\ntoo many listeners have been added to an event:
$ 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
In contrast, the following example turns off the default warning output and\nadds a custom handler to the 'warning' event:
$ 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
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.
--trace-warnings
Launching Node.js using the --throw-deprecation command-line flag will\ncause custom deprecation warnings to be thrown as exceptions.
--throw-deprecation
Using the --trace-deprecation command-line flag will cause the custom\ndeprecation to be printed to stderr along with the stack trace.
--trace-deprecation
Using the --no-deprecation command-line flag will suppress all reporting\nof the custom deprecation.
--no-deprecation
The *-deprecation command-line flags only affect warnings that use the name\n'DeprecationWarning'.
*-deprecation
'DeprecationWarning'
The 'worker' event is emitted after a new <Worker> thread has been created.
'worker'
See the process.emitWarning() method for issuing\ncustom or application-specific warnings.
process.emitWarning()
There are no strict guidelines for warning types (as identified by the name\nproperty) emitted by Node.js. New types of warnings can be added at any time.\nA few of the warning types that are most common include:
name
'code'
'ExperimentalWarning'
'MaxListenersExceededWarning'
EventTarget
'TimeoutOverflowWarning'
setTimeout()
setInterval()
'UnsupportedWarning'
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.
signal(7)
'SIGINT'
'SIGHUP'
Signals are not available on Worker threads.
Worker
The signal handler will receive the signal's name ('SIGINT',\n'SIGTERM', etc.) as the first argument.
'SIGTERM'
The name of each event will be the uppercase common name for the signal (e.g.\n'SIGINT' for SIGINT signals).
SIGINT
import process from 'node:process';\n\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
const process = require('node:process');\n\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
'SIGUSR1'
128 + signal number
'SIGPIPE'
SIGHUP
'SIGBREAK'
'SIGWINCH'
'SIGKILL'
'SIGSTOP'
'SIGBUS'
'SIGFPE'
'SIGSEGV'
'SIGILL'
kill(2)
0
Windows does not support signals so has no equivalent to termination by signal,\nbut Node.js offers some emulation with process.kill(), and\nsubprocess.kill():
process.kill()
subprocess.kill()
SIGTERM
SIGKILL
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:
1
2
3
4
5
FATAL ERROR
6
7
domain.on('error')
8
9
10
12
--inspect
--inspect-brk
13
await
>128
128
SIGABRT
134
The process.abort() method causes the Node.js process to exit immediately and\ngenerate a core file.
process.abort()
This feature is not available in Worker threads.
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).
process.chdir()
directory
import { chdir, cwd } from 'node:process';\n\nconsole.log(`Starting directory: ${cwd()}`);\ntry {\n chdir('/tmp');\n console.log(`New directory: ${cwd()}`);\n} catch (err) {\n console.error(`chdir: ${err}`);\n}\n
const { chdir, cwd } = require('node:process');\n\nconsole.log(`Starting directory: ${cwd()}`);\ntry {\n chdir('/tmp');\n console.log(`New directory: ${cwd()}`);\n} catch (err) {\n console.error(`chdir: ${err}`);\n}\n
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.
process.cpuUsage()
user
system
The result of a previous call to process.cpuUsage() can be passed as the\nargument to the function, to get a diff reading.
import { cpuUsage } from 'node:process';\n\nconst startUsage = 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(cpuUsage(startUsage));\n// { user: 514883, system: 11226 }\n
const { cpuUsage } = require('node:process');\n\nconst startUsage = 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(cpuUsage(startUsage));\n// { user: 514883, system: 11226 }\n
The process.cwd() method returns the current working directory of the Node.js\nprocess.
process.cwd()
import { cwd } from 'node:process';\n\nconsole.log(`Current directory: ${cwd()}`);\n
const { cwd } = require('node:process');\n\nconsole.log(`Current directory: ${cwd()}`);\n
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.
process.disconnect()
The effect of calling process.disconnect() is the same as calling\nChildProcess.disconnect() from the parent process.
ChildProcess.disconnect()
If the Node.js process was not spawned with an IPC channel,\nprocess.disconnect() will be undefined.
undefined
The process.dlopen() method allows dynamically loading shared objects. It is\nprimarily used by require() to load C++ Addons, and should not be used\ndirectly, except in special cases. In other words, require() should be\npreferred over process.dlopen() unless there are specific reasons such as\ncustom dlopen flags or loading from ES modules.
process.dlopen()
require()
The flags argument is an integer that allows to specify dlopen\nbehavior. See the os.constants.dlopen documentation for details.
flags
os.constants.dlopen
An important requirement when calling process.dlopen() is that the module\ninstance must be passed. Functions exported by the C++ Addon are then\naccessible via module.exports.
module
module.exports
The example below shows how to load a C++ Addon, named local.node,\nthat exports a foo function. All the symbols are loaded before\nthe call returns, by passing the RTLD_NOW constant. In this example\nthe constant is assumed to be available.
local.node
foo
RTLD_NOW
import { dlopen } from 'node:process';\nimport { constants } from 'node:os';\nimport { fileURLToPath } from 'node:url';\n\nconst module = { exports: {} };\ndlopen(module, fileURLToPath(new URL('local.node', import.meta.url)),\n constants.dlopen.RTLD_NOW);\nmodule.exports.foo();\n
const { dlopen } = require('node:process');\nconst { constants } = require('node:os');\nconst { join } = require('node:path');\n\nconst module = { exports: {} };\ndlopen(module, join(__dirname, 'local.node'), constants.dlopen.RTLD_NOW);\nmodule.exports.foo();\n
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.
import { emitWarning } from 'node:process';\n\n// Emit a warning with a code and additional detail.\nemitWarning('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
const { emitWarning } = require('node:process');\n\n// Emit a warning with a code and additional detail.\nemitWarning('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
In this example, an Error object is generated internally by\nprocess.emitWarning() and passed through to the\n'warning' handler.
Error
import process from 'node:process';\n\nprocess.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
const process = require('node:process');\n\nprocess.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
If warning is passed as an Error object, the options argument is ignored.
warning
options
import { emitWarning } from 'node:process';\n\n// Emit a warning using a string.\nemitWarning('Something happened!');\n// Emits: (node: 56338) Warning: Something happened!\n
const { emitWarning } = require('node:process');\n\n// Emit a warning using a string.\nemitWarning('Something happened!');\n// Emits: (node: 56338) Warning: Something happened!\n
import { emitWarning } from 'node:process';\n\n// Emit a warning using a string and a type.\nemitWarning('Something Happened!', 'CustomWarning');\n// Emits: (node:56338) CustomWarning: Something Happened!\n
const { emitWarning } = require('node:process');\n\n// Emit a warning using a string and a type.\nemitWarning('Something Happened!', 'CustomWarning');\n// Emits: (node:56338) CustomWarning: Something Happened!\n
import { emitWarning } from 'node:process';\n\nemitWarning('Something happened!', 'CustomWarning', 'WARN001');\n// Emits: (node:56338) [WARN001] CustomWarning: Something happened!\n
const { emitWarning } = require('node:process');\n\nprocess.emitWarning('Something happened!', 'CustomWarning', 'WARN001');\n// Emits: (node:56338) [WARN001] CustomWarning: Something happened!\n
In each of the previous examples, an Error object is generated internally by\nprocess.emitWarning() and passed through to the 'warning'\nhandler.
import process from 'node:process';\n\nprocess.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
const process = require('node:process');\n\nprocess.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
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):
type
code
ctor
import { emitWarning } from 'node:process';\n\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\nemitWarning(myWarning);\n// Emits: (node:56338) [WARN001] CustomWarning: Something happened!\n
const { emitWarning } = require('node:process');\n\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\nemitWarning(myWarning);\n// Emits: (node:56338) [WARN001] CustomWarning: Something happened!\n
A TypeError is thrown if warning is anything other than a string or Error\nobject.
TypeError
While process warnings use Error objects, the process warning\nmechanism is not a replacement for normal error handling mechanisms.
The following additional handling is implemented if the warning type is\n'DeprecationWarning':
As a best practice, warnings should be emitted only once per process. To do\nso, place the emitWarning() behind a boolean.
emitWarning()
import { emitWarning } from 'node:process';\n\nfunction emitMyWarning() {\n if (!emitMyWarning.warned) {\n emitMyWarning.warned = true;\n emitWarning('Only warn once!');\n }\n}\nemitMyWarning();\n// Emits: (node: 56339) Warning: Only warn once!\nemitMyWarning();\n// Emits nothing\n
const { emitWarning } = require('node:process');\n\nfunction emitMyWarning() {\n if (!emitMyWarning.warned) {\n emitMyWarning.warned = true;\n emitWarning('Only warn once!');\n }\n}\nemitMyWarning();\n// Emits: (node: 56339) Warning: Only warn once!\nemitMyWarning();\n// Emits nothing\n
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.
To exit with a 'failure' code:
import { exit } from 'node:process';\n\nexit(1);\n
const { exit } = require('node:process');\n\nexit(1);\n
The shell that executed Node.js should see the exit code as 1.
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.
process.stdout
process.stderr
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.
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:
import { exit } from 'node:process';\n\n// This is an example of what *not* to do:\nif (someConditionNotMet()) {\n printUsageToStdout();\n exit(1);\n}\n
const { exit } = require('node:process');\n\n// This is an example of what *not* to do:\nif (someConditionNotMet()) {\n printUsageToStdout();\n exit(1);\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.
stdout
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:
import process from 'node:process';\n\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
const process = require('node:process');\n\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
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().
In Worker threads, this function stops the current thread rather\nthan the current process.
The process.getActiveResourcesInfo() method returns an array of strings\ncontaining the types of the active resources that are currently keeping the\nevent loop alive.
process.getActiveResourcesInfo()
import { getActiveResourcesInfo } from 'node:process';\nimport { setTimeout } from 'node:timers';\n\nconsole.log('Before:', getActiveResourcesInfo());\nsetTimeout(() => {}, 1000);\nconsole.log('After:', getActiveResourcesInfo());\n// Prints:\n// Before: [ 'CloseReq', 'TTYWrap', 'TTYWrap', 'TTYWrap' ]\n// After: [ 'CloseReq', 'TTYWrap', 'TTYWrap', 'TTYWrap', 'Timeout' ]\n
const { getActiveResourcesInfo } = require('node:process');\nconst { setTimeout } = require('node:timers');\n\nconsole.log('Before:', getActiveResourcesInfo());\nsetTimeout(() => {}, 1000);\nconsole.log('After:', getActiveResourcesInfo());\n// Prints:\n// Before: [ 'TTYWrap', 'TTYWrap', 'TTYWrap' ]\n// After: [ 'TTYWrap', 'TTYWrap', 'TTYWrap', 'Timeout' ]\n
The process.getegid() method returns the numerical effective group identity\nof the Node.js process. (See getegid(2).)
process.getegid()
getegid(2)
import process from 'node:process';\n\nif (process.getegid) {\n console.log(`Current gid: ${process.getegid()}`);\n}\n
const process = require('node:process');\n\nif (process.getegid) {\n console.log(`Current gid: ${process.getegid()}`);\n}\n
This function is only available on POSIX platforms (i.e. not Windows or\nAndroid).
The process.geteuid() method returns the numerical effective user identity of\nthe process. (See geteuid(2).)
process.geteuid()
geteuid(2)
import process from 'node:process';\n\nif (process.geteuid) {\n console.log(`Current uid: ${process.geteuid()}`);\n}\n
const process = require('node:process');\n\nif (process.geteuid) {\n console.log(`Current uid: ${process.geteuid()}`);\n}\n
The process.getgid() method returns the numerical group identity of the\nprocess. (See getgid(2).)
process.getgid()
getgid(2)
import process from 'node:process';\n\nif (process.getgid) {\n console.log(`Current gid: ${process.getgid()}`);\n}\n
const process = require('node:process');\n\nif (process.getgid) {\n console.log(`Current gid: ${process.getgid()}`);\n}\n
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.
process.getgroups()
import process from 'node:process';\n\nif (process.getgroups) {\n console.log(process.getgroups()); // [ 16, 21, 297 ]\n}\n
const process = require('node:process');\n\nif (process.getgroups) {\n console.log(process.getgroups()); // [ 16, 21, 297 ]\n}\n
The process.getuid() method returns the numeric user identity of the process.\n(See getuid(2).)
process.getuid()
getuid(2)
import process from 'node:process';\n\nif (process.getuid) {\n console.log(`Current uid: ${process.getuid()}`);\n}\n
const process = require('node:process');\n\nif (process.getuid) {\n console.log(`Current uid: ${process.getuid()}`);\n}\n
Indicates whether a callback has been set using\nprocess.setUncaughtExceptionCaptureCallback().
This is the legacy version of process.hrtime.bigint()\nbefore bigint was introduced in JavaScript.
process.hrtime.bigint()
bigint
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.
process.hrtime()
[seconds, nanoseconds]
Array
nanoseconds
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.
time
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:
import { hrtime } from 'node:process';\n\nconst NS_PER_SEC = 1e9;\nconst time = hrtime();\n// [ 1800216, 25 ]\n\nsetTimeout(() => {\n const diff = 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
const { hrtime } = require('node:process');\n\nconst NS_PER_SEC = 1e9;\nconst time = hrtime();\n// [ 1800216, 25 ]\n\nsetTimeout(() => {\n const diff = 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
The bigint version of the process.hrtime() method returning the\ncurrent high-resolution real time in nanoseconds as a bigint.
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.
import { hrtime } from 'node:process';\n\nconst start = hrtime.bigint();\n// 191051479007711n\n\nsetTimeout(() => {\n const end = hrtime.bigint();\n // 191052633396993n\n\n console.log(`Benchmark took ${end - start} nanoseconds`);\n // Benchmark took 1154389282 nanoseconds\n}, 1000);\n
const { hrtime } = require('node:process');\n\nconst start = hrtime.bigint();\n// 191051479007711n\n\nsetTimeout(() => {\n const end = hrtime.bigint();\n // 191052633396993n\n\n console.log(`Benchmark took ${end - start} nanoseconds`);\n // Benchmark took 1154389282 nanoseconds\n}, 1000);\n
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.
process.initgroups()
/etc/group
root
CAP_SETGID
Use care when dropping privileges:
import { getgroups, initgroups, setgid } from 'node:process';\n\nconsole.log(getgroups()); // [ 0 ]\ninitgroups('nodeuser', 1000); // switch user\nconsole.log(getgroups()); // [ 27, 30, 46, 1000, 0 ]\nsetgid(1000); // drop root gid\nconsole.log(getgroups()); // [ 27, 30, 46, 1000 ]\n
const { getgroups, initgroups, setgid } = require('node:process');\n\nconsole.log(getgroups()); // [ 0 ]\ninitgroups('nodeuser', 1000); // switch user\nconsole.log(getgroups()); // [ 27, 30, 46, 1000, 0 ]\nsetgid(1000); // drop root gid\nconsole.log(getgroups()); // [ 27, 30, 46, 1000 ]\n
This function is only available on POSIX platforms (i.e. not Windows or\nAndroid).\nThis feature is not available in Worker threads.
The process.kill() method sends the signal to the process identified by\npid.
signal
pid
Signal names are strings such as 'SIGINT' or 'SIGHUP'. See Signal Events\nand kill(2) for more information.
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.
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.
kill
import process, { kill } from 'node:process';\n\nprocess.on('SIGHUP', () => {\n console.log('Got SIGHUP signal.');\n});\n\nsetTimeout(() => {\n console.log('Exiting.');\n process.exit(0);\n}, 100);\n\nkill(process.pid, 'SIGHUP');\n
const process = require('node:process');\n\nprocess.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
When SIGUSR1 is received by a Node.js process, Node.js will start the\ndebugger. See Signal Events.
SIGUSR1
Returns an object describing the memory usage of the Node.js process measured in\nbytes.
import { memoryUsage } from 'node:process';\n\nconsole.log(memoryUsage());\n// Prints:\n// {\n// rss: 4935680,\n// heapTotal: 1826816,\n// heapUsed: 650472,\n// external: 49879,\n// arrayBuffers: 9386\n// }\n
const { memoryUsage } = require('node:process');\n\nconsole.log(memoryUsage());\n// Prints:\n// {\n// rss: 4935680,\n// heapTotal: 1826816,\n// heapUsed: 650472,\n// external: 49879,\n// arrayBuffers: 9386\n// }\n
heapTotal
heapUsed
external
rss
arrayBuffers
ArrayBuffer
SharedArrayBuffer
Buffer
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.
The process.memoryUsage() method iterates over each page to gather\ninformation about memory usage which might be slow depending on the\nprogram memory allocations.
process.memoryUsage()
The process.memoryUsage.rss() method returns an integer representing the\nResident Set Size (RSS) in bytes.
process.memoryUsage.rss()
The Resident Set Size, is the amount of space occupied in the main\nmemory device (that is a subset of the total allocated memory) for the\nprocess, including all C++ and JavaScript objects and code.
This is the same value as the rss property provided by process.memoryUsage()\nbut process.memoryUsage.rss() is faster.
import { memoryUsage } from 'node:process';\n\nconsole.log(memoryUsage.rss());\n// 35655680\n
const { rss } = require('node:process');\n\nconsole.log(memoryUsage.rss());\n// 35655680\n
process.nextTick() adds callback to the \"next tick queue\". This queue is\nfully drained after the current operation on the JavaScript stack runs to\ncompletion and before the event loop is allowed to continue. It's possible to\ncreate an infinite loop if one were to recursively call process.nextTick().\nSee the Event Loop guide for more background.
process.nextTick()
callback
import { nextTick } from 'node:process';\n\nconsole.log('start');\nnextTick(() => {\n console.log('nextTick callback');\n});\nconsole.log('scheduled');\n// Output:\n// start\n// scheduled\n// nextTick callback\n
const { nextTick } = require('node:process');\n\nconsole.log('start');\nnextTick(() => {\n console.log('nextTick callback');\n});\nconsole.log('scheduled');\n// Output:\n// start\n// scheduled\n// nextTick callback\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:
import { nextTick } from 'node:process';\n\nfunction MyThing(options) {\n this.setupOptions(options);\n\n nextTick(() => {\n this.startDoingStuff();\n });\n}\n\nconst thing = new MyThing();\nthing.getReadyForStuff();\n\n// thing.startDoingStuff() gets called now, not before.\n
const { nextTick } = require('node:process');\n\nfunction MyThing(options) {\n this.setupOptions(options);\n\n nextTick(() => {\n this.startDoingStuff();\n });\n}\n\nconst thing = new MyThing();\nthing.getReadyForStuff();\n\n// thing.startDoingStuff() gets called now, not before.\n
It is very important for APIs to be either 100% synchronous or 100%\nasynchronous. Consider this example:
// 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
This API is hazardous because in the following case:
const maybeTrue = Math.random() > 0.5;\n\nmaybeSync(maybeTrue, () => {\n foo();\n});\n\nbar();\n
It is not clear whether foo() or bar() will be called first.
foo()
bar()
The following approach is much better:
import { nextTick } from 'node:process';\n\nfunction definitelyAsync(arg, cb) {\n if (arg) {\n nextTick(cb);\n return;\n }\n\n fs.stat('file', cb);\n}\n
const { nextTick } = require('node:process');\n\nfunction definitelyAsync(arg, cb) {\n if (arg) {\n nextTick(cb);\n return;\n }\n\n fs.stat('file', cb);\n}\n
The queueMicrotask() API is an alternative to process.nextTick() that\nalso defers execution of a function using the same microtask queue used to\nexecute the then, catch, and finally handlers of resolved promises. Within\nNode.js, every time the \"next tick queue\" is drained, the microtask queue\nis drained immediately after.
queueMicrotask()
import { nextTick } from 'node:process';\n\nPromise.resolve().then(() => console.log(2));\nqueueMicrotask(() => console.log(3));\nnextTick(() => console.log(1));\n// Output:\n// 1\n// 2\n// 3\n
const { nextTick } = require('node:process');\n\nPromise.resolve().then(() => console.log(2));\nqueueMicrotask(() => console.log(3));\nnextTick(() => console.log(1));\n// Output:\n// 1\n// 2\n// 3\n
For most userland use cases, the queueMicrotask() API provides a portable\nand reliable mechanism for deferring execution that works across multiple\nJavaScript platform environments and should be favored over process.nextTick().\nIn simple scenarios, queueMicrotask() can be a drop-in replacement for\nprocess.nextTick().
console.log('start');\nqueueMicrotask(() => {\n console.log('microtask callback');\n});\nconsole.log('scheduled');\n// Output:\n// start\n// scheduled\n// microtask callback\n
One note-worthy difference between the two APIs is that process.nextTick()\nallows specifying additional values that will be passed as arguments to the\ndeferred function when it is called. Achieving the same result with\nqueueMicrotask() requires using either a closure or a bound function:
function deferred(a, b) {\n console.log('microtask', a + b);\n}\n\nconsole.log('start');\nqueueMicrotask(deferred.bind(undefined, 1, 2));\nconsole.log('scheduled');\n// Output:\n// start\n// scheduled\n// microtask 3\n
There are minor differences in the way errors raised from within the next tick\nqueue and microtask queue are handled. Errors thrown within a queued microtask\ncallback should be handled within the queued callback when possible. If they are\nnot, the process.on('uncaughtException') event handler can be used to capture\nand handle the errors.
process.on('uncaughtException')
When in doubt, unless the specific capabilities of process.nextTick() are\nneeded, use queueMicrotask().
import { resourceUsage } from 'node:process';\n\nconsole.log(resourceUsage());\n/*\n Will output:\n {\n userCPUTime: 82872,\n systemCPUTime: 4143,\n maxRSS: 33164,\n sharedMemorySize: 0,\n unsharedDataSize: 0,\n unsharedStackSize: 0,\n minorPageFault: 2469,\n majorPageFault: 0,\n swappedOut: 0,\n fsRead: 0,\n fsWrite: 8,\n ipcSent: 0,\n ipcReceived: 0,\n signalsCount: 0,\n voluntaryContextSwitches: 79,\n involuntaryContextSwitches: 1\n }\n*/\n
const { resourceUsage } = require('node:process');\n\nconsole.log(resourceUsage());\n/*\n Will output:\n {\n userCPUTime: 82872,\n systemCPUTime: 4143,\n maxRSS: 33164,\n sharedMemorySize: 0,\n unsharedDataSize: 0,\n unsharedStackSize: 0,\n minorPageFault: 2469,\n majorPageFault: 0,\n swappedOut: 0,\n fsRead: 0,\n fsWrite: 8,\n ipcSent: 0,\n ipcReceived: 0,\n signalsCount: 0,\n voluntaryContextSwitches: 79,\n involuntaryContextSwitches: 1\n }\n*/\n
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.
process.send()
ChildProcess
If Node.js was not spawned with an IPC channel, process.send will be\nundefined.
process.send
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.
process.setegid()
setegid(2)
id
import process from 'node:process';\n\nif (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
const process = require('node:process');\n\nif (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
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.
process.seteuid()
seteuid(2)
import process from 'node:process';\n\nif (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
const process = require('node:process');\n\nif (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
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.
process.setgid()
setgid(2)
import process from 'node:process';\n\nif (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
const process = require('node:process');\n\nif (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
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.
process.setgroups()
The groups array can contain numeric group IDs, group names, or both.
groups
import process from 'node:process';\n\nif (process.getgroups && process.setgroups) {\n try {\n process.setgroups([501]);\n console.log(process.getgroups()); // new groups\n } catch (err) {\n console.log(`Failed to set groups: ${err}`);\n }\n}\n
const process = require('node:process');\n\nif (process.getgroups && process.setgroups) {\n try {\n process.setgroups([501]);\n console.log(process.getgroups()); // new groups\n } catch (err) {\n console.log(`Failed to set groups: ${err}`);\n }\n}\n
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.
process.setuid(id)
setuid(2)
import process from 'node:process';\n\nif (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
const process = require('node:process');\n\nif (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
This function enables or disables the Source Map v3 support for\nstack traces.
It provides same features as launching Node.js process with commandline options\n--enable-source-maps.
--enable-source-maps
Only source maps in JavaScript files that are loaded after source maps has been\nenabled will be parsed and loaded.
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.
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. Actions configured to take place on exceptions such as report\ngenerations will be affected too
--abort-on-uncaught-exception
v8.setFlagsFromString()
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.
process.setUncaughtExceptionCaptureCallback(null)
null
Using this function is mutually exclusive with using the deprecated\ndomain built-in module.
domain
process.umask() returns the Node.js process's file mode creation mask. Child\nprocesses inherit the mask from the parent process.
process.umask()
process.umask(mask) sets the Node.js process's file mode creation mask. Child\nprocesses inherit the mask from the parent process. Returns the previous mask.
process.umask(mask)
import { umask } from 'node:process';\n\nconst newmask = 0o022;\nconst oldmask = umask(newmask);\nconsole.log(\n `Changed umask from ${oldmask.toString(8)} to ${newmask.toString(8)}`\n);\n
const { umask } = require('node:process');\n\nconst newmask = 0o022;\nconst oldmask = umask(newmask);\nconsole.log(\n `Changed umask from ${oldmask.toString(8)} to ${newmask.toString(8)}`\n);\n
In Worker threads, process.umask(mask) will throw an exception.
The process.uptime() method returns the number of seconds the current Node.js\nprocess has been running.
process.uptime()
The return value includes fractions of a second. Use Math.floor() to get whole\nseconds.
Math.floor()
The process.allowedNodeEnvironmentFlags property is a special,\nread-only Set of flags allowable within the NODE_OPTIONS\nenvironment variable.
process.allowedNodeEnvironmentFlags
Set
NODE_OPTIONS
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:
Set.prototype.has
process.allowedNodeEnvironmentFlags.has()
true
-
--
inspect-brk
r
-r
--v8-options
--perf_basic_prof
--perf-basic-prof
--perf_basic-prof
=
--stack-trace-limit=100
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:
import { allowedNodeEnvironmentFlags } from 'node:process';\n\nallowedNodeEnvironmentFlags.forEach((flag) => {\n // -r\n // --inspect-brk\n // --abort_on_uncaught_exception\n // ...\n});\n
const { allowedNodeEnvironmentFlags } = require('node:process');\n\nallowedNodeEnvironmentFlags.forEach((flag) => {\n // -r\n // --inspect-brk\n // --abort_on_uncaught_exception\n // ...\n});\n
The methods add(), clear(), and delete() of\nprocess.allowedNodeEnvironmentFlags do nothing, and will fail\nsilently.
add()
clear()
delete()
If Node.js was compiled without NODE_OPTIONS support (shown in\nprocess.config), process.allowedNodeEnvironmentFlags will\ncontain what would have been allowable.
process.config
The operating system CPU architecture for which the Node.js binary was compiled.\nPossible values are: 'arm', 'arm64', 'ia32', 'mips','mipsel', 'ppc',\n'ppc64', 's390', 's390x', and 'x64'.
'arm'
'arm64'
'ia32'
'mips'
'mipsel'
'ppc'
'ppc64'
's390'
's390x'
'x64'
import { arch } from 'node:process';\n\nconsole.log(`This processor architecture is ${arch}`);\n
const { arch } = require('node:process');\n\nconsole.log(`This processor architecture is ${arch}`);\n
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\nof argv[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.
process.argv
process.execPath
process.argv0
argv[0]
For example, assuming the following script for process-args.js:
process-args.js
import { argv } from 'node:process';\n\n// print process.argv\nargv.forEach((val, index) => {\n console.log(`${index}: ${val}`);\n});\n
const { argv } = require('node:process');\n\n// print process.argv\nargv.forEach((val, index) => {\n console.log(`${index}: ${val}`);\n});\n
Launching the Node.js process as:
$ node process-args.js one two=three four\n
Would generate the output:
0: /usr/local/bin/node\n1: /Users/mjr/work/node/process-args.js\n2: one\n3: two=three\n4: four\n
The process.argv0 property stores a read-only copy of the original value of\nargv[0] passed when Node.js starts.
$ bash -c 'exec -a customArgv0 ./node'\n> process.argv[0]\n'/Volumes/code/external/node/out/Release/node'\n> process.argv0\n'customArgv0'\n
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.
process.channel
This method makes the IPC channel keep the event loop of the process\nrunning if .unref() has been called before.
.unref()
Typically, this is managed through the number of 'disconnect' and 'message'\nlisteners on the process object. However, this method can be used to\nexplicitly request a specific behavior.
This method makes the IPC channel not keep the event loop of the process\nrunning, and lets it finish even while the channel is open.
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.
Object
config.gypi
./configure
An example of the possible output looks like:
{\n target_defaults:\n { cflags: [],\n default_configuration: 'Release',\n defines: [],\n include_dirs: [],\n libraries: [] },\n variables:\n {\n host_arch: 'x64',\n napi_build_version: 5,\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: 1\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.
Modifying the process.config property, or any child-property of the\nprocess.config object has been deprecated. The process.config will be made\nread-only in a future release.
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.
process.connected
false
Once process.connected is false, it is no longer possible to send messages\nover the IPC channel using process.send().
The port used by the Node.js debugger when enabled.
import process from 'node:process';\n\nprocess.debugPort = 5858;\n
const process = require('node:process');\n\nprocess.debugPort = 5858;\n
The process.env property returns an object containing the user environment.\nSee environ(7).
process.env
environ(7)
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
It is possible to modify this object, but such modifications will not be\nreflected outside the Node.js process, or (unless explicitly requested)\nto other Worker threads.\nIn other words, the following example would not work:
$ node -e 'process.env.foo = \"bar\"' && echo $foo\n
While the following will:
import { env } from 'node:process';\n\nenv.foo = 'bar';\nconsole.log(env.foo);\n
const { env } = require('node:process');\n\nenv.foo = 'bar';\nconsole.log(env.foo);\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.
import { env } from 'node:process';\n\nenv.test = null;\nconsole.log(env.test);\n// => 'null'\nenv.test = undefined;\nconsole.log(env.test);\n// => 'undefined'\n
const { env } = require('node:process');\n\nenv.test = null;\nconsole.log(env.test);\n// => 'null'\nenv.test = undefined;\nconsole.log(env.test);\n// => 'undefined'\n
Use delete to delete a property from process.env.
delete
import { env } from 'node:process';\n\nenv.TEST = 1;\ndelete env.TEST;\nconsole.log(env.TEST);\n// => undefined\n
const { env } = require('node:process');\n\nenv.TEST = 1;\ndelete env.TEST;\nconsole.log(env.TEST);\n// => undefined\n
On Windows operating systems, environment variables are case-insensitive.
import { env } from 'node:process';\n\nenv.TEST = 1;\nconsole.log(env.test);\n// => 1\n
const { env } = require('node:process');\n\nenv.TEST = 1;\nconsole.log(env.test);\n// => 1\n
Unless explicitly specified when creating a Worker instance,\neach Worker thread has its own copy of process.env, based on its\nparent thread's process.env, or whatever was specified as the env option\nto the Worker constructor. Changes to process.env will not be visible\nacross Worker threads, and only the main thread can make changes that\nare visible to the operating system or to native add-ons.
env
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.
process.execArgv
$ node --harmony script.js --version\n
Results in process.execArgv:
['--harmony']\n
And process.argv:
['/usr/local/bin/node', 'script.js', '--version']\n
Refer to Worker constructor for the detailed behavior of worker\nthreads with this property.
The process.execPath property returns the absolute pathname of the executable\nthat started the Node.js process. Symbolic links, if any, are resolved.
'/usr/local/bin/node'\n
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.
Specifying a code to process.exit(code) will override any\nprevious setting of process.exitCode.
process.exit(code)
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.
process.mainModule
require.main
As with require.main, process.mainModule will be undefined if there\nis no entry script.
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.
process.noDeprecation
The process.pid property returns the PID of the process.
process.pid
import { pid } from 'node:process';\n\nconsole.log(`This process is pid ${pid}`);\n
const { pid } = require('node:process');\n\nconsole.log(`This process is pid ${pid}`);\n
The process.platform property returns a string identifying the operating\nsystem platform for which the Node.js binary was compiled.
process.platform
Currently possible values are:
'aix'
'darwin'
'freebsd'
'linux'
'openbsd'
'sunos'
'win32'
import { platform } from 'node:process';\n\nconsole.log(`This platform is ${platform}`);\n
const { platform } = require('node:process');\n\nconsole.log(`This platform is ${platform}`);\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.
'android'
The process.ppid property returns the PID of the parent of the\ncurrent process.
process.ppid
import { ppid } from 'node:process';\n\nconsole.log(`The parent process is pid ${ppid}`);\n
const { ppid } = require('node:process');\n\nconsole.log(`The parent process is pid ${ppid}`);\n
The process.release property returns an Object containing metadata related\nto the current release, including URLs for the source tarball and headers-only\ntarball.
process.release
process.release contains the following properties:
'node'
sourceUrl
.tar.gz
headersUrl
libUrl
node.lib
lts
'Dubnium'
'Erbium'
{\n name: 'node',\n lts: 'Erbium',\n sourceUrl: 'https://nodejs.org/download/release/v12.18.1/node-v12.18.1.tar.gz',\n headersUrl: 'https://nodejs.org/download/release/v12.18.1/node-v12.18.1-headers.tar.gz',\n libUrl: 'https://nodejs.org/download/release/v12.18.1/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.
process.report is an object whose methods are used to generate diagnostic\nreports for the current process. Additional documentation is available in the\nreport documentation.
process.report
Write reports in a compact format, single-line JSON, more easily consumable\nby log processing systems than the default multi-line format designed for\nhuman consumption.
import { report } from 'node:process';\n\nconsole.log(`Reports are compact? ${report.compact}`);\n
const { report } = require('node:process');\n\nconsole.log(`Reports are compact? ${report.compact}`);\n
Directory where the report is written. The default value is the empty string,\nindicating that reports are written to the current working directory of the\nNode.js process.
import { report } from 'node:process';\n\nconsole.log(`Report directory is ${report.directory}`);\n
const { report } = require('node:process');\n\nconsole.log(`Report directory is ${report.directory}`);\n
Filename where the report is written. If set to the empty string, the output\nfilename will be comprised of a timestamp, PID, and sequence number. The default\nvalue is the empty string.
If the value of process.report.filename is set to 'stdout' or 'stderr',\nthe report is written to the stdout or stderr of the process respectively.
process.report.filename
'stdout'
'stderr'
import { report } from 'node:process';\n\nconsole.log(`Report filename is ${report.filename}`);\n
const { report } = require('node:process');\n\nconsole.log(`Report filename is ${report.filename}`);\n
If true, a diagnostic report is generated on fatal errors, such as out of\nmemory errors or failed C++ assertions.
import { report } from 'node:process';\n\nconsole.log(`Report on fatal error: ${report.reportOnFatalError}`);\n
const { report } = require('node:process');\n\nconsole.log(`Report on fatal error: ${report.reportOnFatalError}`);\n
If true, a diagnostic report is generated when the process receives the\nsignal specified by process.report.signal.
process.report.signal
import { report } from 'node:process';\n\nconsole.log(`Report on signal: ${report.reportOnSignal}`);\n
const { report } = require('node:process');\n\nconsole.log(`Report on signal: ${report.reportOnSignal}`);\n
If true, a diagnostic report is generated on uncaught exception.
import { report } from 'node:process';\n\nconsole.log(`Report on exception: ${report.reportOnUncaughtException}`);\n
const { report } = require('node:process');\n\nconsole.log(`Report on exception: ${report.reportOnUncaughtException}`);\n
The signal used to trigger the creation of a diagnostic report. Defaults to\n'SIGUSR2'.
'SIGUSR2'
import { report } from 'node:process';\n\nconsole.log(`Report signal: ${report.signal}`);\n
const { report } = require('node:process');\n\nconsole.log(`Report signal: ${report.signal}`);\n
Returns a JavaScript Object representation of a diagnostic report for the\nrunning process. The report's JavaScript stack trace is taken from err, if\npresent.
err
import { report } from 'node:process';\n\nconst data = report.getReport();\nconsole.log(data.header.nodejsVersion);\n\n// Similar to process.report.writeReport()\nimport fs from 'node:fs';\nfs.writeFileSync('my-report.log', util.inspect(data), 'utf8');\n
const { report } = require('node:process');\n\nconst data = report.getReport();\nconsole.log(data.header.nodejsVersion);\n\n// Similar to process.report.writeReport()\nconst fs = require('node:fs');\nfs.writeFileSync('my-report.log', util.inspect(data), 'utf8');\n
Additional documentation is available in the report documentation.
Writes a diagnostic report to a file. If filename is not provided, the default\nfilename includes the date, time, PID, and a sequence number. The report's\nJavaScript stack trace is taken from err, if present.
filename
If the value of filename is set to 'stdout' or 'stderr', the report is\nwritten to the stdout or stderr of the process respectively.
import { report } from 'node:process';\n\nreport.writeReport();\n
const { report } = require('node:process');\n\nreport.writeReport();\n
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.
net.Socket
process.stderr differs from other Node.js streams in important ways. See\nnote on process I/O for more information.
This property refers to the value of underlying file descriptor of\nprocess.stderr. The value is fixed at 2. In Worker threads,\nthis field does not exist.
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.
process.stdin
stdin
For details of how to read from stdin see readable.read().
readable.read()
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.
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.
process.stdin.resume()
This property refers to the value of underlying file descriptor of\nprocess.stdin. The value is fixed at 0. In Worker threads,\nthis field does not exist.
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.
For example, to copy process.stdin to process.stdout:
import { stdin, stdout } from 'node:process';\n\nstdin.pipe(stdout);\n
const { stdin, stdout } = require('node:process');\n\nstdin.pipe(stdout);\n
process.stdout differs from other Node.js streams in important ways. See\nnote on process I/O for more information.
This property refers to the value of underlying file descriptor of\nprocess.stdout. The value is fixed at 1. In Worker threads,\nthis field does not exist.
process.stdout and process.stderr differ from other Node.js streams in\nimportant ways:
console.log()
console.error()
These behaviors are partly for historical reasons, as changing them would\ncreate backward incompatibility, but they are also expected by some users.
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.
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, it's 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.
To check if a stream is connected to a TTY context, check the isTTY\nproperty.
isTTY
For instance:
$ 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
See the TTY documentation for more information.
The initial value of process.throwDeprecation indicates whether the\n--throw-deprecation flag is set on the current Node.js process.\nprocess.throwDeprecation is mutable, so whether or not deprecation\nwarnings result in errors may be altered at runtime. See the\ndocumentation for the 'warning' event and the\nemitWarning() method for more information.
process.throwDeprecation
$ node --throw-deprecation -p \"process.throwDeprecation\"\ntrue\n$ node -p \"process.throwDeprecation\"\nundefined\n$ node\n> process.emitWarning('test', 'DeprecationWarning');\nundefined\n> (node:26598) DeprecationWarning: test\n> process.throwDeprecation = true;\ntrue\n> process.emitWarning('test', 'DeprecationWarning');\nThrown:\n[DeprecationWarning: test] { name: 'DeprecationWarning' }\n
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.
process.title
ps
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.
argv
environ
Assigning a value to process.title might not result in an accurate label\nwithin process manager applications such as macOS Activity Monitor or Windows\nServices Manager.
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.
process.traceDeprecation
The process.version property contains the Node.js version string.
process.version
import { version } from 'node:process';\n\nconsole.log(`Version: ${version}`);\n// Version: v14.8.0\n
const { version } = require('node:process');\n\nconsole.log(`Version: ${version}`);\n// Version: v14.8.0\n
To get the version string without the prepended v, use\nprocess.versions.node.
process.versions.node
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.
process.versions
process.versions.modules
import { versions } from 'node:process';\n\nconsole.log(versions);\n
const { versions } = require('node:process');\n\nconsole.log(versions);\n
Will generate an object similar to:
{ node: '11.13.0',\n v8: '7.0.276.38-node.18',\n uv: '1.27.0',\n zlib: '1.2.11',\n brotli: '1.0.7',\n ares: '1.15.0',\n modules: '67',\n nghttp2: '1.34.0',\n napi: '4',\n llhttp: '1.1.1',\n openssl: '1.1.1b',\n cldr: '34.0',\n icu: '63.1',\n tz: '2018e',\n unicode: '11.0' }\n