Process#

Source Code:lib/process.js

Theprocess object provides information about, and control over, the currentNode.js process.

import processfrom'node:process';const process =require('node:process');

Process events#

Theprocess object is an instance ofEventEmitter.

Event:'beforeExit'#

Added in: v0.11.12

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

The listener callback function is invoked with the value ofprocess.exitCode passed as the only argument.

The'beforeExit' event isnot emitted for conditions causing explicittermination, such as callingprocess.exit() or uncaught exceptions.

The'beforeExit' shouldnot be used as an alternative to the'exit' eventunless the intention is to schedule additional work.

import processfrom'node:process';process.on('beforeExit',(code) => {console.log('Process beforeExit event with code: ', code);});process.on('exit',(code) => {console.log('Process exit event with code: ', code);});console.log('This message is displayed first.');// Prints:// This message is displayed first.// Process beforeExit event with code: 0// Process exit event with code: 0const process =require('node:process');process.on('beforeExit',(code) => {console.log('Process beforeExit event with code: ', code);});process.on('exit',(code) => {console.log('Process exit event with code: ', code);});console.log('This message is displayed first.');// Prints:// This message is displayed first.// Process beforeExit event with code: 0// Process exit event with code: 0

Event:'disconnect'#

Added in: v0.7.7

If the Node.js process is spawned with an IPC channel (see theChild ProcessandCluster documentation), the'disconnect' event will be emitted whenthe IPC channel is closed.

Event:'exit'#

Added in: v0.1.7

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

  • Theprocess.exit() method being called explicitly;
  • The Node.js event loop no longer having any additional work to perform.

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

The listener callback function is invoked with the exit code specified eitherby theprocess.exitCode property, or theexitCode argument passed to theprocess.exit() method.

import processfrom'node:process';process.on('exit',(code) => {console.log(`About to exit with code:${code}`);});const process =require('node:process');process.on('exit',(code) => {console.log(`About to exit with code:${code}`);});

Listener functionsmust only performsynchronous operations. The Node.jsprocess will exit immediately after calling the'exit' event listenerscausing any additional work still queued in the event loop to be abandoned.In the following example, for instance, the timeout will never occur:

import processfrom'node:process';process.on('exit',(code) => {setTimeout(() => {console.log('This will not run');  },0);});const process =require('node:process');process.on('exit',(code) => {setTimeout(() => {console.log('This will not run');  },0);});

Event:'message'#

Added in: v0.5.10

If the Node.js process is spawned with an IPC channel (see theChild ProcessandCluster documentation), the'message' event is emitted whenever amessage sent by a parent process usingchildprocess.send() is received bythe child process.

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

If theserialization option was set toadvanced used when spawning theprocess, themessage argument can contain data that JSON is not ableto represent.SeeAdvanced serialization forchild_process for more details.

Event:'multipleResolves'#

Added in: v10.12.0Deprecated since: v17.6.0, v16.15.0

Stability: 0 - Deprecated

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

The'multipleResolves' event is emitted whenever aPromise has been either:

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

This is useful for tracking potential errors in an application while using thePromise constructor, as multiple resolutions are silently swallowed. However,the occurrence of this event does not necessarily indicate an error. Forexample,Promise.race() can trigger a'multipleResolves' event.

Because of the unreliability of the event in cases like thePromise.race() example above it has been deprecated.

import processfrom'node:process';process.on('multipleResolves',(type, promise, reason) => {console.error(type, promise, reason);setImmediate(() => process.exit(1));});asyncfunctionmain() {try {returnawaitnewPromise((resolve, reject) => {resolve('First call');resolve('Swallowed resolve');reject(newError('Swallowed reject'));    });  }catch {thrownewError('Failed');  }}main().then(console.log);// resolve: Promise { 'First call' } 'Swallowed resolve'// reject: Promise { 'First call' } Error: Swallowed reject//     at Promise (*)//     at new Promise (<anonymous>)//     at main (*)// First callconst process =require('node:process');process.on('multipleResolves',(type, promise, reason) => {console.error(type, promise, reason);setImmediate(() => process.exit(1));});asyncfunctionmain() {try {returnawaitnewPromise((resolve, reject) => {resolve('First call');resolve('Swallowed resolve');reject(newError('Swallowed reject'));    });  }catch {thrownewError('Failed');  }}main().then(console.log);// resolve: Promise { 'First call' } 'Swallowed resolve'// reject: Promise { 'First call' } Error: Swallowed reject//     at Promise (*)//     at new Promise (<anonymous>)//     at main (*)// First call

Event:'rejectionHandled'#

Added in: v1.4.1

The'rejectionHandled' event is emitted whenever aPromise has been rejectedand an error handler was attached to it (usingpromise.catch(), forexample) later than one turn of the Node.js event loop.

ThePromise object would have previously been emitted in an'unhandledRejection' event, but during the course of processing gained arejection handler.

There is no notion of a top level for aPromise chain at which rejections canalways be handled. Being inherently asynchronous in nature, aPromiserejection can be handled at a future point in time, possibly much later thanthe 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 isan ever-growing list of unhandled exceptions, with Promises there can be agrowing-and-shrinking list of unhandled rejections.

In synchronous code, the'uncaughtException' event is emitted when the list ofunhandled exceptions grows.

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

import processfrom'node:process';const unhandledRejections =newMap();process.on('unhandledRejection',(reason, promise) => {  unhandledRejections.set(promise, reason);});process.on('rejectionHandled',(promise) => {  unhandledRejections.delete(promise);});const process =require('node:process');const unhandledRejections =newMap();process.on('unhandledRejection',(reason, promise) => {  unhandledRejections.set(promise, reason);});process.on('rejectionHandled',(promise) => {  unhandledRejections.delete(promise);});

In this example, theunhandledRejectionsMap will grow and shrink over time,reflecting rejections that start unhandled and then become handled. It ispossible to record such errors in an error log, either periodically (which islikely best for long-running application) or upon process exit (which is likelymost convenient for scripts).

Event:'workerMessage'#

Added in: v22.5.0, v20.19.0

The'workerMessage' event is emitted for any incoming message send by the otherparty by usingpostMessageToThread().

Event:'uncaughtException'#

History
VersionChanges
v12.0.0, v10.17.0

Added theorigin argument.

v0.1.18

Added in: v0.1.18

  • err<Error> The uncaught exception.
  • origin<string> Indicates if the exception originates from an unhandledrejection or from a synchronous error. Can either be'uncaughtException' or'unhandledRejection'. The latter is used when an exception happens in aPromise based async context (or if aPromise is rejected) and--unhandled-rejections flag set tostrict orthrow (which is thedefault) and the rejection is not handled, or when a rejection happens duringthe command line entry point's ES module static loading phase.

The'uncaughtException' event is emitted when an uncaught JavaScriptexception bubbles all the way back to the event loop. By default, Node.jshandles such exceptions by printing the stack trace tostderr and exitingwith code 1, overriding any previously setprocess.exitCode.Adding a handler for the'uncaughtException' event overrides this defaultbehavior. Alternatively, change theprocess.exitCode in the'uncaughtException' handler which will result in the process exiting with theprovided exit code. Otherwise, in the presence of such handler the process willexit with 0.

import processfrom'node:process';import fsfrom'node:fs';process.on('uncaughtException',(err, origin) => {  fs.writeSync(    process.stderr.fd,`Caught exception:${err}\n` +`Exception origin:${origin}\n`,  );});setTimeout(() => {console.log('This will still run.');},500);// Intentionally cause an exception, but don't catch it.nonexistentFunc();console.log('This will not run.');const process =require('node:process');const fs =require('node:fs');process.on('uncaughtException',(err, origin) => {  fs.writeSync(    process.stderr.fd,`Caught exception:${err}\n` +`Exception origin:${origin}\n`,  );});setTimeout(() => {console.log('This will still run.');},500);// Intentionally cause an exception, but don't catch it.nonexistentFunc();console.log('This will not run.');

It is possible to monitor'uncaughtException' events without overriding thedefault behavior to exit the process by installing a'uncaughtExceptionMonitor' listener.

Warning: Using'uncaughtException' correctly#

'uncaughtException' is a crude mechanism for exception handlingintended to be used only as a last resort. The eventshould not be used asan equivalent toOn Error Resume Next. Unhandled exceptions inherently meanthat an application is in an undefined state. Attempting to resume applicationcode without properly recovering from the exception can cause additionalunforeseen and unpredictable issues.

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

Attempting to resume normally after an uncaught exception can be similar topulling out the power cord when upgrading a computer. Nine out of tentimes, nothing happens. But the tenth time, the system becomes corrupted.

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

To restart a crashed application in a more reliable way, whether'uncaughtException' is emitted or not, an external monitor should be employedin a separate process to detect application failures and recover or restart asneeded.

Event:'uncaughtExceptionMonitor'#

Added in: v13.7.0, v12.17.0
  • err<Error> The uncaught exception.
  • origin<string> Indicates if the exception originates from an unhandledrejection or from synchronous errors. Can either be'uncaughtException' or'unhandledRejection'. The latter is used when an exception happens in aPromise based async context (or if aPromise is rejected) and--unhandled-rejections flag set tostrict orthrow (which is thedefault) and the rejection is not handled, or when a rejection happens duringthe command line entry point's ES module static loading phase.

The'uncaughtExceptionMonitor' event is emitted before an'uncaughtException' event is emitted or a hook installed viaprocess.setUncaughtExceptionCaptureCallback() is called.

Installing an'uncaughtExceptionMonitor' listener does not change the behavioronce an'uncaughtException' event is emitted. The process willstill crash if no'uncaughtException' listener is installed.

import processfrom'node:process';process.on('uncaughtExceptionMonitor',(err, origin) => {MyMonitoringTool.logSync(err, origin);});// Intentionally cause an exception, but don't catch it.nonexistentFunc();// Still crashes Node.jsconst process =require('node:process');process.on('uncaughtExceptionMonitor',(err, origin) => {MyMonitoringTool.logSync(err, origin);});// Intentionally cause an exception, but don't catch it.nonexistentFunc();// Still crashes Node.js

Event:'unhandledRejection'#

History
VersionChanges
v7.0.0

Not handlingPromise rejections is deprecated.

v6.6.0

UnhandledPromise rejections will now emit a process warning.

v1.4.1

Added in: v1.4.1

  • reason<Error> |<any> The object with which the promise was rejected(typically anError object).
  • promise<Promise> The rejected promise.

The'unhandledRejection' event is emitted whenever aPromise is rejected andno error handler is attached to the promise within a turn of the event loop.When programming with Promises, exceptions are encapsulated as "rejectedpromises". Rejections can be caught and handled usingpromise.catch() andare propagated through aPromise chain. The'unhandledRejection' event isuseful for detecting and keeping track of promises that were rejected whoserejections have not yet been handled.

import processfrom'node:process';process.on('unhandledRejection',(reason, promise) => {console.log('Unhandled Rejection at:', promise,'reason:', reason);// Application specific logging, throwing an error, or other logic here});somePromise.then((res) => {returnreportToUser(JSON.pasre(res));// Note the typo (`pasre`)});// No `.catch()` or `.then()`const process =require('node:process');process.on('unhandledRejection',(reason, promise) => {console.log('Unhandled Rejection at:', promise,'reason:', reason);// Application specific logging, throwing an error, or other logic here});somePromise.then((res) => {returnreportToUser(JSON.pasre(res));// Note the typo (`pasre`)});// No `.catch()` or `.then()`

The following will also trigger the'unhandledRejection' event to beemitted:

import processfrom'node:process';functionSomeResource() {// Initially set the loaded status to a rejected promisethis.loaded =Promise.reject(newError('Resource not yet loaded!'));}const resource =newSomeResource();// no .catch or .then on resource.loaded for at least a turnconst process =require('node:process');functionSomeResource() {// Initially set the loaded status to a rejected promisethis.loaded =Promise.reject(newError('Resource not yet loaded!'));}const resource =newSomeResource();// no .catch or .then on resource.loaded for at least a turn

In this example case, it is possible to track the rejection as a developer erroras would typically be the case for other'unhandledRejection' events. Toaddress such failures, a non-operational.catch(() => { }) handler may be attached toresource.loaded, which would prevent the'unhandledRejection' event frombeing emitted.

If an'unhandledRejection' event is emitted but not handled it willbe raised as an uncaught exception. This alongside other behaviors of'unhandledRejection' events can changed via the--unhandled-rejections flag.

Event:'warning'#

Added in: v6.0.0
  • warning<Error> Key properties of the warning are:
    • name<string> The name of the warning.Default:'Warning'.
    • message<string> A system-provided description of the warning.
    • stack<string> A stack trace to the location in the code where the warningwas issued.

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

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

import processfrom'node:process';process.on('warning',(warning) => {console.warn(warning.name);// Print the warning nameconsole.warn(warning.message);// Print the warning messageconsole.warn(warning.stack);// Print the stack trace});const process =require('node:process');process.on('warning',(warning) => {console.warn(warning.name);// Print the warning nameconsole.warn(warning.message);// Print the warning messageconsole.warn(warning.stack);// Print the stack trace});

By default, Node.js will print process warnings tostderr. The--no-warningscommand-line option can be used to suppress the default console output but the'warning' event will still be emitted by theprocess object. Currently, itis not possible to suppress specific warning types other than deprecationwarnings. To suppress deprecation warnings, check out the--no-deprecationflag.

The following example illustrates the warning that is printed tostderr whentoo many listeners have been added to an event:

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

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

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

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

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

Using the--trace-deprecation command-line flag will cause the customdeprecation to be printed tostderr along with the stack trace.

Using the--no-deprecation command-line flag will suppress all reportingof the custom deprecation.

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

Emitting custom warnings#

See theprocess.emitWarning() method for issuingcustom or application-specific warnings.

Node.js warning names#

There are no strict guidelines for warning types (as identified by thenameproperty) emitted by Node.js. New types of warnings can be added at any time.A few of the warning types that are most common include:

  • 'DeprecationWarning' - Indicates use of a deprecated Node.js API or feature.Such warnings must include a'code' property identifying thedeprecation code.
  • 'ExperimentalWarning' - Indicates use of an experimental Node.js API orfeature. Such features must be used with caution as they may change at anytime and are not subject to the same strict semantic-versioning and long-termsupport policies as supported features.
  • 'MaxListenersExceededWarning' - Indicates that too many listeners for agiven event have been registered on either anEventEmitter orEventTarget.This is often an indication of a memory leak.
  • 'TimeoutOverflowWarning' - Indicates that a numeric value that cannot fitwithin a 32-bit signed integer has been provided to either thesetTimeout()orsetInterval() functions.
  • 'TimeoutNegativeWarning' - Indicates that a negative number has provided toeither thesetTimeout() orsetInterval() functions.
  • 'TimeoutNaNWarning' - Indicates that a value which is not a number hasprovided to either thesetTimeout() orsetInterval() functions.
  • 'UnsupportedWarning' - Indicates use of an unsupported option or featurethat will be ignored rather than treated as an error. One example is use ofthe HTTP response status message when using the HTTP/2 compatibility API.

Event:'worker'#

Added in: v16.2.0, v14.18.0

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

Signal events#

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

Signals are not available onWorker threads.

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

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

import processfrom'node:process';// Begin reading from stdin so the process does not exit.process.stdin.resume();process.on('SIGINT',() => {console.log('Received SIGINT. Press Control-D to exit.');});// Using a single function to handle multiple signalsfunctionhandle(signal) {console.log(`Received${signal}`);}process.on('SIGINT', handle);process.on('SIGTERM', handle);const process =require('node:process');// Begin reading from stdin so the process does not exit.process.stdin.resume();process.on('SIGINT',() => {console.log('Received SIGINT. Press Control-D to exit.');});// Using a single function to handle multiple signalsfunctionhandle(signal) {console.log(`Received${signal}`);}process.on('SIGINT', handle);process.on('SIGTERM', handle);
  • 'SIGUSR1' is reserved by Node.js to start thedebugger. It's possible toinstall a listener but doing so might interfere with the debugger.
  • 'SIGTERM' and'SIGINT' have default handlers on non-Windows platforms thatreset the terminal mode before exiting with code128 + signal number. If oneof these signals has a listener installed, its default behavior will beremoved (Node.js will no longer exit).
  • 'SIGPIPE' is ignored by default. It can have a listener installed.
  • 'SIGHUP' is generated on Windows when the console window is closed, and onother platforms under various similar conditions. Seesignal(7). It can have alistener installed, however Node.js will be unconditionally terminated byWindows about 10 seconds later. On non-Windows platforms, the defaultbehavior ofSIGHUP is to terminate Node.js, but once a listener has beeninstalled its default behavior will be removed.
  • 'SIGTERM' is not supported on Windows, it can be listened on.
  • 'SIGINT' from the terminal is supported on all platforms, and can usually begenerated withCtrl+C (though this may be configurable).It is not generated whenterminal raw mode is enabledandCtrl+C is used.
  • 'SIGBREAK' is delivered on Windows whenCtrl+Break ispressed. On non-Windows platforms, it can be listened on, but there is no wayto send or generate it.
  • 'SIGWINCH' is delivered when the console has been resized. On Windows, thiswill only happen on write to the console when the cursor is being moved, orwhen a readable tty is used in raw mode.
  • 'SIGKILL' cannot have a listener installed, it will unconditionallyterminate Node.js on all platforms.
  • 'SIGSTOP' cannot have a listener installed.
  • 'SIGBUS','SIGFPE','SIGSEGV', and'SIGILL', when not raisedartificially usingkill(2), inherently leave the process in a state fromwhich it is not safe to call JS listeners. Doing so might cause the processto stop responding.
  • 0 can be sent to test for the existence of a process, it has no effect ifthe process exists, but will throw an error if the process does not exist.

Windows does not support signals so has no equivalent to termination by signal,but Node.js offers some emulation withprocess.kill(), andsubprocess.kill():

  • SendingSIGINT,SIGTERM, andSIGKILL will cause the unconditionaltermination of the target process, and afterwards, subprocess will report thatthe process was terminated by signal.
  • Sending signal0 can be used as a platform independent way to test for theexistence of a process.

process.abort()#

Added in: v0.7.0

Theprocess.abort() method causes the Node.js process to exit immediately andgenerate a core file.

This feature is not available inWorker threads.

process.allowedNodeEnvironmentFlags#

Added in: v10.10.0

Theprocess.allowedNodeEnvironmentFlags property is a special,read-onlySet of flags allowable within theNODE_OPTIONSenvironment variable.

process.allowedNodeEnvironmentFlags extendsSet, but overridesSet.prototype.has to recognize several different possible flagrepresentations.process.allowedNodeEnvironmentFlags.has() willreturntrue in the following cases:

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

When iterating overprocess.allowedNodeEnvironmentFlags, flags willappear onlyonce; each will begin with one or more dashes. Flagspassed through to V8 will contain underscores instead of non-leadingdashes:

import { allowedNodeEnvironmentFlags }from'node:process';allowedNodeEnvironmentFlags.forEach((flag) => {// -r// --inspect-brk// --abort_on_uncaught_exception// ...});const { allowedNodeEnvironmentFlags } =require('node:process');allowedNodeEnvironmentFlags.forEach((flag) => {// -r// --inspect-brk// --abort_on_uncaught_exception// ...});

The methodsadd(),clear(), anddelete() ofprocess.allowedNodeEnvironmentFlags do nothing, and will failsilently.

If Node.js was compiledwithoutNODE_OPTIONS support (shown inprocess.config),process.allowedNodeEnvironmentFlags willcontain whatwould have been allowable.

process.arch#

Added in: v0.5.0

The operating system CPU architecture for which the Node.js binary was compiled.Possible values are:'arm','arm64','ia32','loong64','mips','mipsel','ppc64','riscv64','s390','s390x', and'x64'.

import { arch }from'node:process';console.log(`This processor architecture is${arch}`);const { arch } =require('node:process');console.log(`This processor architecture is${arch}`);

process.argv#

Added in: v0.1.27

Theprocess.argv property returns an array containing the command-linearguments passed when the Node.js process was launched. The first element willbeprocess.execPath. Seeprocess.argv0 if access to the original valueofargv[0] is needed. The second element will be the path to the JavaScriptfile being executed. The remaining elements will be any additional command-linearguments.

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

import { argv }from'node:process';// print process.argvargv.forEach((val, index) => {console.log(`${index}:${val}`);});const { argv } =require('node:process');// print process.argvargv.forEach((val, index) => {console.log(`${index}:${val}`);});

Launching the Node.js process as:

node process-args.js one two=three four

Would generate the output:

0: /usr/local/bin/node1: /Users/mjr/work/node/process-args.js2: one3: two=three4: four

process.argv0#

Added in: v6.4.0

Theprocess.argv0 property stores a read-only copy of the original value ofargv[0] passed when Node.js starts.

$bash -c'exec -a customArgv0 ./node'>process.argv[0]'/Volumes/code/external/node/out/Release/node'>process.argv0'customArgv0'

process.availableMemory()#

History
VersionChanges
v24.0.0

Change stability index for this feature from Experimental to Stable.

v22.0.0, v20.13.0

Added in: v22.0.0, v20.13.0

Gets the amount of free memory that is still available to the process(in bytes).

Seeuv_get_available_memory for moreinformation.

process.channel#

History
VersionChanges
v14.0.0

The object no longer accidentally exposes native C++ bindings.

v7.1.0

Added in: v7.1.0

If the Node.js process was spawned with an IPC channel (see theChild Process documentation), theprocess.channelproperty is a reference to the IPC channel. If no IPC channel exists, thisproperty isundefined.

process.channel.ref()#

Added in: v7.1.0

This method makes the IPC channel keep the event loop of the processrunning if.unref() has been called before.

Typically, this is managed through the number of'disconnect' and'message'listeners on theprocess object. However, this method can be used toexplicitly request a specific behavior.

process.channel.unref()#

Added in: v7.1.0

This method makes the IPC channel not keep the event loop of the processrunning, and lets it finish even while the channel is open.

Typically, this is managed through the number of'disconnect' and'message'listeners on theprocess object. However, this method can be used toexplicitly request a specific behavior.

process.chdir(directory)#

Added in: v0.1.17

Theprocess.chdir() method changes the current working directory of theNode.js process or throws an exception if doing so fails (for instance, ifthe specifieddirectory does not exist).

import { chdir, cwd }from'node:process';console.log(`Starting directory:${cwd()}`);try {chdir('/tmp');console.log(`New directory:${cwd()}`);}catch (err) {console.error(`chdir:${err}`);}const { chdir, cwd } =require('node:process');console.log(`Starting directory:${cwd()}`);try {chdir('/tmp');console.log(`New directory:${cwd()}`);}catch (err) {console.error(`chdir:${err}`);}

This feature is not available inWorker threads.

process.config#

History
VersionChanges
v19.0.0

Theprocess.config object is now frozen.

v16.0.0

Modifying process.config has been deprecated.

v0.7.7

Added in: v0.7.7

Theprocess.config property returns a frozenObject containing theJavaScript representation of the configure options used to compile the currentNode.js executable. This is the same as theconfig.gypi file that was producedwhen running the./configure script.

An example of the possible output looks like:

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

process.connected#

Added in: v0.7.2

If the Node.js process is spawned with an IPC channel (see theChild ProcessandCluster documentation), theprocess.connected property will returntrue so long as the IPC channel is connected and will returnfalse afterprocess.disconnect() is called.

Onceprocess.connected isfalse, it is no longer possible to send messagesover the IPC channel usingprocess.send().

process.constrainedMemory()#

History
VersionChanges
v24.0.0

Change stability index for this feature from Experimental to Stable.

v22.0.0, v20.13.0

Aligned return value withuv_get_constrained_memory.

v19.6.0, v18.15.0

Added in: v19.6.0, v18.15.0

Gets the amount of memory available to the process (in bytes) based onlimits imposed by the OS. If there is no such constraint, or the constraintis unknown,0 is returned.

Seeuv_get_constrained_memory for moreinformation.

process.cpuUsage([previousValue])#

Added in: v6.1.0

Theprocess.cpuUsage() method returns the user and system CPU time usage ofthe current process, in an object with propertiesuser andsystem, whosevalues are microsecond values (millionth of a second). These values measure timespent in user and system code respectively, and may end up being greater thanactual elapsed time if multiple CPU cores are performing work for this process.

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

import { cpuUsage }from'node:process';const startUsage =cpuUsage();// { user: 38579, system: 6986 }// spin the CPU for 500 millisecondsconst now =Date.now();while (Date.now() - now <500);console.log(cpuUsage(startUsage));// { user: 514883, system: 11226 }const { cpuUsage } =require('node:process');const startUsage =cpuUsage();// { user: 38579, system: 6986 }// spin the CPU for 500 millisecondsconst now =Date.now();while (Date.now() - now <500);console.log(cpuUsage(startUsage));// { user: 514883, system: 11226 }

process.cwd()#

Added in: v0.1.8

Theprocess.cwd() method returns the current working directory of the Node.jsprocess.

import { cwd }from'node:process';console.log(`Current directory:${cwd()}`);const { cwd } =require('node:process');console.log(`Current directory:${cwd()}`);

process.debugPort#

Added in: v0.7.2

The port used by the Node.js debugger when enabled.

import processfrom'node:process';process.debugPort =5858;const process =require('node:process');process.debugPort =5858;

process.disconnect()#

Added in: v0.7.2

If the Node.js process is spawned with an IPC channel (see theChild ProcessandCluster documentation), theprocess.disconnect() method will close theIPC channel to the parent process, allowing the child process to exit gracefullyonce there are no other connections keeping it alive.

The effect of callingprocess.disconnect() is the same as callingChildProcess.disconnect() from the parent process.

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

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

History
VersionChanges
v9.0.0

Added support for theflags argument.

v0.1.16

Added in: v0.1.16

Theprocess.dlopen() method allows dynamically loading shared objects. It isprimarily used byrequire() to load C++ Addons, and should not be useddirectly, except in special cases. In other words,require() should bepreferred overprocess.dlopen() unless there are specific reasons such ascustom dlopen flags or loading from ES modules.

Theflags argument is an integer that allows to specify dlopenbehavior. See theos.constants.dlopen documentation for details.

An important requirement when callingprocess.dlopen() is that themoduleinstance must be passed. Functions exported by the C++ Addon are thenaccessible viamodule.exports.

The example below shows how to load a C++ Addon, namedlocal.node,that exports afoo function. All the symbols are loaded beforethe call returns, by passing theRTLD_NOW constant. In this examplethe constant is assumed to be available.

import { dlopen }from'node:process';import { constants }from'node:os';import { fileURLToPath }from'node:url';constmodule = {exports: {} };dlopen(module,fileURLToPath(newURL('local.node',import.meta.url)),       constants.dlopen.RTLD_NOW);module.exports.foo();const { dlopen } =require('node:process');const { constants } =require('node:os');const { join } =require('node:path');constmodule = {exports: {} };dlopen(module,join(__dirname,'local.node'), constants.dlopen.RTLD_NOW);module.exports.foo();

process.emitWarning(warning[, options])#

Added in: v8.0.0
  • warning<string> |<Error> The warning to emit.
  • options<Object>
    • type<string> Whenwarning is aString,type is the name to usefor thetype of warning being emitted.Default:'Warning'.
    • code<string> A unique identifier for the warning instance being emitted.
    • ctor<Function> Whenwarning is aString,ctor is an optionalfunction used to limit the generated stack trace.Default:process.emitWarning.
    • detail<string> Additional text to include with the error.

Theprocess.emitWarning() method can be used to emit custom or applicationspecific process warnings. These can be listened for by adding a handler to the'warning' event.

import { emitWarning }from'node:process';// Emit a warning with a code and additional detail.emitWarning('Something happened!', {code:'MY_WARNING',detail:'This is some additional information',});// Emits:// (node:56338) [MY_WARNING] Warning: Something happened!// This is some additional informationconst { emitWarning } =require('node:process');// Emit a warning with a code and additional detail.emitWarning('Something happened!', {code:'MY_WARNING',detail:'This is some additional information',});// Emits:// (node:56338) [MY_WARNING] Warning: Something happened!// This is some additional information

In this example, anError object is generated internally byprocess.emitWarning() and passed through to the'warning' handler.

import processfrom'node:process';process.on('warning',(warning) => {console.warn(warning.name);// 'Warning'console.warn(warning.message);// 'Something happened!'console.warn(warning.code);// 'MY_WARNING'console.warn(warning.stack);// Stack traceconsole.warn(warning.detail);// 'This is some additional information'});const process =require('node:process');process.on('warning',(warning) => {console.warn(warning.name);// 'Warning'console.warn(warning.message);// 'Something happened!'console.warn(warning.code);// 'MY_WARNING'console.warn(warning.stack);// Stack traceconsole.warn(warning.detail);// 'This is some additional information'});

Ifwarning is passed as anError object, theoptions argument is ignored.

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

Added in: v6.0.0
  • warning<string> |<Error> The warning to emit.
  • type<string> Whenwarning is aString,type is the name to usefor thetype of warning being emitted.Default:'Warning'.
  • code<string> A unique identifier for the warning instance being emitted.
  • ctor<Function> Whenwarning is aString,ctor is an optionalfunction used to limit the generated stack trace.Default:process.emitWarning.

Theprocess.emitWarning() method can be used to emit custom or applicationspecific process warnings. These can be listened for by adding a handler to the'warning' event.

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

In each of the previous examples, anError object is generated internally byprocess.emitWarning() and passed through to the'warning'handler.

import processfrom'node:process';process.on('warning',(warning) => {console.warn(warning.name);console.warn(warning.message);console.warn(warning.code);console.warn(warning.stack);});const process =require('node:process');process.on('warning',(warning) => {console.warn(warning.name);console.warn(warning.message);console.warn(warning.code);console.warn(warning.stack);});

Ifwarning is passed as anError object, it will be passed through to the'warning' event handler unmodified (and the optionaltype,code andctor arguments will be ignored):

import { emitWarning }from'node:process';// Emit a warning using an Error object.const myWarning =newError('Something happened!');// Use the Error name property to specify the type namemyWarning.name ='CustomWarning';myWarning.code ='WARN001';emitWarning(myWarning);// Emits: (node:56338) [WARN001] CustomWarning: Something happened!const { emitWarning } =require('node:process');// Emit a warning using an Error object.const myWarning =newError('Something happened!');// Use the Error name property to specify the type namemyWarning.name ='CustomWarning';myWarning.code ='WARN001';emitWarning(myWarning);// Emits: (node:56338) [WARN001] CustomWarning: Something happened!

ATypeError is thrown ifwarning is anything other than a string orErrorobject.

While process warnings useError objects, the process warningmechanism isnot a replacement for normal error handling mechanisms.

The following additional handling is implemented if the warningtype is'DeprecationWarning':

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

Avoiding duplicate warnings#

As a best practice, warnings should be emitted only once per process. To doso, place theemitWarning() behind a boolean.

import { emitWarning }from'node:process';functionemitMyWarning() {if (!emitMyWarning.warned) {    emitMyWarning.warned =true;emitWarning('Only warn once!');  }}emitMyWarning();// Emits: (node: 56339) Warning: Only warn once!emitMyWarning();// Emits nothingconst { emitWarning } =require('node:process');functionemitMyWarning() {if (!emitMyWarning.warned) {    emitMyWarning.warned =true;emitWarning('Only warn once!');  }}emitMyWarning();// Emits: (node: 56339) Warning: Only warn once!emitMyWarning();// Emits nothing

process.env#

History
VersionChanges
v11.14.0

Worker threads will now use a copy of the parent thread'sprocess.env by default, configurable through theenv option of theWorker constructor.

v10.0.0

Implicit conversion of variable value to string is deprecated.

v0.1.27

Added in: v0.1.27

Theprocess.env property returns an object containing the user environment.Seeenviron(7).

An example of this object looks like:

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

It is possible to modify this object, but such modifications will not bereflected outside the Node.js process, or (unless explicitly requested)to otherWorker threads.In other words, the following example would not work:

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

While the following will:

import { env }from'node:process';env.foo ='bar';console.log(env.foo);const { env } =require('node:process');env.foo ='bar';console.log(env.foo);

Assigning a property onprocess.env will implicitly convert the valueto a string.This behavior is deprecated. Future versions of Node.js maythrow an error when the value is not a string, number, or boolean.

import { env }from'node:process';env.test =null;console.log(env.test);// => 'null'env.test =undefined;console.log(env.test);// => 'undefined'const { env } =require('node:process');env.test =null;console.log(env.test);// => 'null'env.test =undefined;console.log(env.test);// => 'undefined'

Usedelete to delete a property fromprocess.env.

import { env }from'node:process';env.TEST =1;delete env.TEST;console.log(env.TEST);// => undefinedconst { env } =require('node:process');env.TEST =1;delete env.TEST;console.log(env.TEST);// => undefined

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

import { env }from'node:process';env.TEST =1;console.log(env.test);// => 1const { env } =require('node:process');env.TEST =1;console.log(env.test);// => 1

Unless explicitly specified when creating aWorker instance,eachWorker thread has its own copy ofprocess.env, based on itsparent thread'sprocess.env, or whatever was specified as theenv optionto theWorker constructor. Changes toprocess.env will not be visibleacrossWorker threads, and only the main thread can make changes thatare visible to the operating system or to native add-ons. On Windows, a copy ofprocess.env on aWorker instance operates in a case-sensitive mannerunlike the main thread.

process.execArgv#

Added in: v0.7.7

Theprocess.execArgv property returns the set of Node.js-specific command-lineoptions passed when the Node.js process was launched. These options do notappear in the array returned by theprocess.argv property, and do notinclude the Node.js executable, the name of the script, or any options followingthe script name. These options are useful in order to spawn child processes withthe same execution environment as the parent.

node --icu-data-dir=./foo --require ./bar.js script.js --version

Results inprocess.execArgv:

["--icu-data-dir=./foo","--require","./bar.js"]

Andprocess.argv:

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

Refer toWorker constructor for the detailed behavior of workerthreads with this property.

process.execPath#

Added in: v0.1.100

Theprocess.execPath property returns the absolute pathname of the executablethat started the Node.js process. Symbolic links, if any, are resolved.

'/usr/local/bin/node'

process.execve(file[, args[, env]])#

Added in: v23.11.0, v22.15.0

Stability: 1 - Experimental

  • file<string> The name or path of the executable file to run.
  • args<string[]> List of string arguments. No argument can contain a null-byte (\u0000).
  • env<Object> Environment key-value pairs.No key or value can contain a null-byte (\u0000).Default:process.env.

Replaces the current process with a new process.

This is achieved by using theexecve POSIX function and therefore no memory or otherresources from the current process are preserved, except for the standard input,standard output and standard error file descriptor.

All other resources are discarded by the system when the processes are swapped, without triggeringany exit or close events and without running any cleanup handler.

This function will never return, unless an error occurred.

This function is not available on Windows or IBM i.

process.exit([code])#

History
VersionChanges
v20.0.0

Only accepts a code of type number, or of type string if it represents an integer.

v0.1.13

Added in: v0.1.13

Theprocess.exit() method instructs Node.js to terminate the processsynchronously with an exit status ofcode. Ifcode is omitted, exit useseither the 'success' code0 or the value ofprocess.exitCode if it has beenset. Node.js will not terminate until all the'exit' event listeners arecalled.

To exit with a 'failure' code:

import { exit }from'node:process';exit(1);const { exit } =require('node:process');exit(1);

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

Callingprocess.exit() will force the process to exit as quickly as possibleeven if there are still asynchronous operations pending that have not yetcompleted fully, including I/O operations toprocess.stdout andprocess.stderr.

In most situations, it is not actually necessary to callprocess.exit()explicitly. The Node.js process will exit on its ownif there is no additionalwork pending in the event loop. Theprocess.exitCode property can be set totell the process which exit code to use when the process exits gracefully.

For instance, the following example illustrates amisuse of theprocess.exit() method that could lead to data printed to stdout beingtruncated and lost:

import { exit }from'node:process';// This is an example of what *not* to do:if (someConditionNotMet()) {printUsageToStdout();exit(1);}const { exit } =require('node:process');// This is an example of what *not* to do:if (someConditionNotMet()) {printUsageToStdout();exit(1);}

The reason this is problematic is because writes toprocess.stdout in Node.jsare sometimesasynchronous and may occur over multiple ticks of the Node.jsevent loop. Callingprocess.exit(), however, forces the process to exitbefore those additional writes tostdout can be performed.

Rather than callingprocess.exit() directly, the codeshould set theprocess.exitCode and allow the process to exit naturally by avoidingscheduling any additional work for the event loop:

import processfrom'node:process';// How to properly set the exit code while letting// the process exit gracefully.if (someConditionNotMet()) {printUsageToStdout();  process.exitCode =1;}const process =require('node:process');// How to properly set the exit code while letting// the process exit gracefully.if (someConditionNotMet()) {printUsageToStdout();  process.exitCode =1;}

If it is necessary to terminate the Node.js process due to an error condition,throwing anuncaught error and allowing the process to terminate accordinglyis safer than callingprocess.exit().

InWorker threads, this function stops the current thread ratherthan the current process.

process.exitCode#

History
VersionChanges
v20.0.0

Only accepts a code of type number, or of type string if it represents an integer.

v0.11.8

Added in: v0.11.8

A number which will be the process exit code, when the process eitherexits gracefully, or is exited viaprocess.exit() without specifyinga code.

The value ofprocess.exitCode can be updated by either assigning a value toprocess.exitCode or by passing an argument toprocess.exit():

$node -e'process.exitCode = 9';echo $?9$node -e'process.exit(42)';echo $?42$node -e'process.exitCode = 9; process.exit(42)';echo $?42

The value can also be set implicitly by Node.js when unrecoverable errors occur (e.g.such as the encountering of an unsettled top-level await). However explicitmanipulations of the exit code always take precedence over implicit ones:

$node --input-type=module -e'await new Promise(() => {})';echo $?13$node --input-type=module -e'process.exitCode = 9; await new Promise(() => {})';echo $?9

process.features.cached_builtins#

Added in: v12.0.0

A boolean value that istrue if the current Node.js build is caching builtin modules.

process.features.debug#

Added in: v0.5.5

A boolean value that istrue if the current Node.js build is a debug build.

process.features.inspector#

Added in: v11.10.0

A boolean value that istrue if the current Node.js build includes the inspector.

process.features.ipv6#

Added in: v0.5.3Deprecated since: v23.4.0, v22.13.0

Stability: 0 - Deprecated. This property is always true, and any checks based on it areredundant.

A boolean value that istrue if the current Node.js build includes support for IPv6.

Since all Node.js builds have IPv6 support, this value is alwaystrue.

process.features.require_module#

Added in: v23.0.0, v22.10.0, v20.19.0

A boolean value that istrue if the current Node.js build supportsloading ECMAScript modules usingrequire().

process.features.tls#

Added in: v0.5.3

A boolean value that istrue if the current Node.js build includes support for TLS.

process.features.tls_alpn#

Added in: v4.8.0Deprecated since: v23.4.0, v22.13.0

Stability: 0 - Deprecated. Useprocess.features.tls instead.

A boolean value that istrue if the current Node.js build includes support for ALPN in TLS.

In Node.js 11.0.0 and later versions, the OpenSSL dependencies feature unconditional ALPN support.This value is therefore identical to that ofprocess.features.tls.

process.features.tls_ocsp#

Added in: v0.11.13Deprecated since: v23.4.0, v22.13.0

Stability: 0 - Deprecated. Useprocess.features.tls instead.

A boolean value that istrue if the current Node.js build includes support for OCSP in TLS.

In Node.js 11.0.0 and later versions, the OpenSSL dependencies feature unconditional OCSP support.This value is therefore identical to that ofprocess.features.tls.

process.features.tls_sni#

Added in: v0.5.3Deprecated since: v23.4.0, v22.13.0

Stability: 0 - Deprecated. Useprocess.features.tls instead.

A boolean value that istrue if the current Node.js build includes support for SNI in TLS.

In Node.js 11.0.0 and later versions, the OpenSSL dependencies feature unconditional SNI support.This value is therefore identical to that ofprocess.features.tls.

process.features.typescript#

Added in: v23.0.0, v22.10.0

Stability: 1.2 - Release candidate

A value that is"strip" by default,"transform" if Node.js is run with--experimental-transform-types, andfalse ifNode.js is run with--no-experimental-strip-types.

process.features.uv#

Added in: v0.5.3Deprecated since: v23.4.0, v22.13.0

Stability: 0 - Deprecated. This property is always true, and any checks based on it areredundant.

A boolean value that istrue if the current Node.js build includes support for libuv.

Since it's not possible to build Node.js without libuv, this value is alwaystrue.

process.finalization.register(ref, callback)#

Added in: v22.5.0

Stability: 1.1 - Active Development

  • ref<Object> |<Function> The reference to the resource that is being tracked.
  • callback<Function> The callback function to be called when the resourceis finalized.
    • ref<Object> |<Function> The reference to the resource that is being tracked.
    • event<string> The event that triggered the finalization. Defaults to 'exit'.

This function registers a callback to be called when the process emits theexitevent if theref object was not garbage collected. If the objectref was garbage collectedbefore theexit event is emitted, the callback will be removed from the finalization registry,and it will not be called on process exit.

Inside the callback you can release the resources allocated by theref object.Be aware that all limitations applied to thebeforeExit event are also applied to thecallback function,this means that there is a possibility that the callback will not be called under special circumstances.

The idea of ​​this function is to help you free up resources when the starts process exiting,but also let the object be garbage collected if it is no longer being used.

Eg: you can register an object that contains a buffer, you want to make sure that buffer is releasedwhen the process exit, but if the object is garbage collected before the process exit, we no longerneed to release the buffer, so in this case we just remove the callback from the finalization registry.

const { finalization } =require('node:process');// Please make sure that the function passed to finalization.register()// does not create a closure around unnecessary objects.functiononFinalize(obj, event) {// You can do whatever you want with the object  obj.dispose();}functionsetup() {// This object can be safely garbage collected,// and the resulting shutdown function will not be called.// There are no leaks.const myDisposableObject = {dispose() {// Free your resources synchronously    },  };  finalization.register(myDisposableObject, onFinalize);}setup();import { finalization }from'node:process';// Please make sure that the function passed to finalization.register()// does not create a closure around unnecessary objects.functiononFinalize(obj, event) {// You can do whatever you want with the object  obj.dispose();}functionsetup() {// This object can be safely garbage collected,// and the resulting shutdown function will not be called.// There are no leaks.const myDisposableObject = {dispose() {// Free your resources synchronously    },  };  finalization.register(myDisposableObject, onFinalize);}setup();

The code above relies on the following assumptions:

  • arrow functions are avoided
  • regular functions are recommended to be within the global context (root)

Regular functionscould reference the context where theobj lives, making theobj not garbage collectible.

Arrow functions will hold the previous context. Consider, for example:

classTest {constructor() {    finalization.register(this,(ref) => ref.dispose());// Even something like this is highly discouraged// finalization.register(this, () => this.dispose());  }dispose() {}}

It is very unlikely (not impossible) that this object will be garbage collected,but if it is not,dispose will be called whenprocess.exit is called.

Be careful and avoid relying on this feature for the disposal of critical resources,as it is not guaranteed that the callback will be called under all circumstances.

process.finalization.registerBeforeExit(ref, callback)#

Added in: v22.5.0

Stability: 1.1 - Active Development

  • ref<Object> |<Function> The referenceto the resource that is being tracked.
  • callback<Function> The callback function to be called when the resourceis finalized.
    • ref<Object> |<Function> The reference to the resource that is being tracked.
    • event<string> The event that triggered the finalization. Defaults to 'beforeExit'.

This function behaves exactly like theregister, except that the callback will be calledwhen the process emits thebeforeExit event ifref object was not garbage collected.

Be aware that all limitations applied to thebeforeExit event are also applied to thecallback function,this means that there is a possibility that the callback will not be called under special circumstances.

process.finalization.unregister(ref)#

Added in: v22.5.0

Stability: 1.1 - Active Development

This function remove the register of the object from the finalizationregistry, so the callback will not be called anymore.

const { finalization } =require('node:process');// Please make sure that the function passed to finalization.register()// does not create a closure around unnecessary objects.functiononFinalize(obj, event) {// You can do whatever you want with the object  obj.dispose();}functionsetup() {// This object can be safely garbage collected,// and the resulting shutdown function will not be called.// There are no leaks.const myDisposableObject = {dispose() {// Free your resources synchronously    },  };  finalization.register(myDisposableObject, onFinalize);// Do something  myDisposableObject.dispose();  finalization.unregister(myDisposableObject);}setup();import { finalization }from'node:process';// Please make sure that the function passed to finalization.register()// does not create a closure around unnecessary objects.functiononFinalize(obj, event) {// You can do whatever you want with the object  obj.dispose();}functionsetup() {// This object can be safely garbage collected,// and the resulting shutdown function will not be called.// There are no leaks.const myDisposableObject = {dispose() {// Free your resources synchronously    },  };// Please make sure that the function passed to finalization.register()// does not create a closure around unnecessary objects.functiononFinalize(obj, event) {// You can do whatever you want with the object    obj.dispose();  }  finalization.register(myDisposableObject, onFinalize);// Do something  myDisposableObject.dispose();  finalization.unregister(myDisposableObject);}setup();

process.getActiveResourcesInfo()#

History
VersionChanges
v24.0.0

Change stability index for this feature from Experimental to Stable.

v17.3.0, v16.14.0

Added in: v17.3.0, v16.14.0

Theprocess.getActiveResourcesInfo() method returns an array of stringscontaining the types of the active resources that are currently keeping theevent loop alive.

import { getActiveResourcesInfo }from'node:process';import {setTimeout }from'node:timers';console.log('Before:',getActiveResourcesInfo());setTimeout(() => {},1000);console.log('After:',getActiveResourcesInfo());// Prints://   Before: [ 'CloseReq', 'TTYWrap', 'TTYWrap', 'TTYWrap' ]//   After: [ 'CloseReq', 'TTYWrap', 'TTYWrap', 'TTYWrap', 'Timeout' ]const { getActiveResourcesInfo } =require('node:process');const {setTimeout } =require('node:timers');console.log('Before:',getActiveResourcesInfo());setTimeout(() => {},1000);console.log('After:',getActiveResourcesInfo());// Prints://   Before: [ 'TTYWrap', 'TTYWrap', 'TTYWrap' ]//   After: [ 'TTYWrap', 'TTYWrap', 'TTYWrap', 'Timeout' ]

process.getBuiltinModule(id)#

Added in: v22.3.0, v20.16.0

process.getBuiltinModule(id) provides a way to load built-in modulesin a globally available function. ES Modules that need to supportother environments can use it to conditionally load a Node.js built-inwhen it is run in Node.js, without having to deal with the resolutionerror that can be thrown byimport in a non-Node.js environment orhaving to use dynamicimport() which either turns the module intoan asynchronous module, or turns a synchronous API into an asynchronous one.

if (globalThis.process?.getBuiltinModule) {// Run in Node.js, use the Node.js fs module.const fs = globalThis.process.getBuiltinModule('fs');// If `require()` is needed to load user-modules, use createRequire()constmodule = globalThis.process.getBuiltinModule('module');constrequire =module.createRequire(import.meta.url);const foo =require('foo');}

Ifid specifies a built-in module available in the current Node.js process,process.getBuiltinModule(id) method returns the corresponding built-inmodule. Ifid does not correspond to any built-in module,undefinedis returned.

process.getBuiltinModule(id) accepts built-in module IDs that are recognizedbymodule.isBuiltin(id). Some built-in modules must be loaded with thenode: prefix, seebuilt-in modules with mandatorynode: prefix.The references returned byprocess.getBuiltinModule(id) always point tothe built-in module corresponding toid even if users modifyrequire.cache so thatrequire(id) returns something else.

process.getegid()#

Added in: v2.0.0

Theprocess.getegid() method returns the numerical effective group identityof the Node.js process. (Seegetegid(2).)

import processfrom'node:process';if (process.getegid) {console.log(`Current gid:${process.getegid()}`);}const process =require('node:process');if (process.getegid) {console.log(`Current gid:${process.getegid()}`);}

This function is only available on POSIX platforms (i.e. not Windows orAndroid).

process.geteuid()#

Added in: v2.0.0

Theprocess.geteuid() method returns the numerical effective user identity ofthe process. (Seegeteuid(2).)

import processfrom'node:process';if (process.geteuid) {console.log(`Current uid:${process.geteuid()}`);}const process =require('node:process');if (process.geteuid) {console.log(`Current uid:${process.geteuid()}`);}

This function is only available on POSIX platforms (i.e. not Windows orAndroid).

process.getgid()#

Added in: v0.1.31

Theprocess.getgid() method returns the numerical group identity of theprocess. (Seegetgid(2).)

import processfrom'node:process';if (process.getgid) {console.log(`Current gid:${process.getgid()}`);}const process =require('node:process');if (process.getgid) {console.log(`Current gid:${process.getgid()}`);}

This function is only available on POSIX platforms (i.e. not Windows orAndroid).

process.getgroups()#

Added in: v0.9.4

Theprocess.getgroups() method returns an array with the supplementary groupIDs. POSIX leaves it unspecified if the effective group ID is included butNode.js ensures it always is.

import processfrom'node:process';if (process.getgroups) {console.log(process.getgroups());// [ 16, 21, 297 ]}const process =require('node:process');if (process.getgroups) {console.log(process.getgroups());// [ 16, 21, 297 ]}

This function is only available on POSIX platforms (i.e. not Windows orAndroid).

process.getuid()#

Added in: v0.1.28

Theprocess.getuid() method returns the numeric user identity of the process.(Seegetuid(2).)

import processfrom'node:process';if (process.getuid) {console.log(`Current uid:${process.getuid()}`);}const process =require('node:process');if (process.getuid) {console.log(`Current uid:${process.getuid()}`);}

This function not available on Windows.

process.hasUncaughtExceptionCaptureCallback()#

Added in: v9.3.0

Indicates whether a callback has been set usingprocess.setUncaughtExceptionCaptureCallback().

process.hrtime([time])#

Added in: v0.7.6

Stability: 3 - Legacy. Useprocess.hrtime.bigint() instead.

This is the legacy version ofprocess.hrtime.bigint()beforebigint was introduced in JavaScript.

Theprocess.hrtime() method returns the current high-resolution real timein a[seconds, nanoseconds] tupleArray, wherenanoseconds is theremaining part of the real time that can't be represented in second precision.

time is an optional parameter that must be the result of a previousprocess.hrtime() call to diff with the current time. If the parameterpassed in is not a tupleArray, aTypeError will be thrown. Passing in auser-defined array instead of the result of a previous call toprocess.hrtime() will lead to undefined behavior.

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

import { hrtime }from'node:process';constNS_PER_SEC =1e9;const time =hrtime();// [ 1800216, 25 ]setTimeout(() => {const diff =hrtime(time);// [ 1, 552 ]console.log(`Benchmark took${diff[0] * NS_PER_SEC + diff[1]} nanoseconds`);// Benchmark took 1000000552 nanoseconds},1000);const { hrtime } =require('node:process');constNS_PER_SEC =1e9;const time =hrtime();// [ 1800216, 25 ]setTimeout(() => {const diff =hrtime(time);// [ 1, 552 ]console.log(`Benchmark took${diff[0] * NS_PER_SEC + diff[1]} nanoseconds`);// Benchmark took 1000000552 nanoseconds},1000);

process.hrtime.bigint()#

Added in: v10.7.0

Thebigint version of theprocess.hrtime() method returning thecurrent high-resolution real time in nanoseconds as abigint.

Unlikeprocess.hrtime(), it does not support an additionaltimeargument since the difference can just be computed directlyby subtraction of the twobigints.

import { hrtime }from'node:process';const start = hrtime.bigint();// 191051479007711nsetTimeout(() => {const end = hrtime.bigint();// 191052633396993nconsole.log(`Benchmark took${end - start} nanoseconds`);// Benchmark took 1154389282 nanoseconds},1000);const { hrtime } =require('node:process');const start = hrtime.bigint();// 191051479007711nsetTimeout(() => {const end = hrtime.bigint();// 191052633396993nconsole.log(`Benchmark took${end - start} nanoseconds`);// Benchmark took 1154389282 nanoseconds},1000);

process.initgroups(user, extraGroup)#

Added in: v0.9.4

Theprocess.initgroups() method reads the/etc/group file and initializesthe group access list, using all groups of which the user is a member. This isa privileged operation that requires that the Node.js process either haverootaccess or theCAP_SETGID capability.

Use care when dropping privileges:

import { getgroups, initgroups, setgid }from'node:process';console.log(getgroups());// [ 0 ]initgroups('nodeuser',1000);// switch userconsole.log(getgroups());// [ 27, 30, 46, 1000, 0 ]setgid(1000);// drop root gidconsole.log(getgroups());// [ 27, 30, 46, 1000 ]const { getgroups, initgroups, setgid } =require('node:process');console.log(getgroups());// [ 0 ]initgroups('nodeuser',1000);// switch userconsole.log(getgroups());// [ 27, 30, 46, 1000, 0 ]setgid(1000);// drop root gidconsole.log(getgroups());// [ 27, 30, 46, 1000 ]

This function is only available on POSIX platforms (i.e. not Windows orAndroid).This feature is not available inWorker threads.

process.kill(pid[, signal])#

Added in: v0.0.6

Theprocess.kill() method sends thesignal to the process identified bypid.

Signal names are strings such as'SIGINT' or'SIGHUP'. SeeSignal Eventsandkill(2) for more information.

This method will throw an error if the targetpid does not exist. As a specialcase, a signal of0 can be used to test for the existence of a process.Windows platforms will throw an error if thepid is used to kill a processgroup.

Even though the name of this function isprocess.kill(), it is really just asignal sender, like thekill system call. The signal sent may do somethingother than kill the target process.

import process, { kill }from'node:process';process.on('SIGHUP',() => {console.log('Got SIGHUP signal.');});setTimeout(() => {console.log('Exiting.');  process.exit(0);},100);kill(process.pid,'SIGHUP');const process =require('node:process');process.on('SIGHUP',() => {console.log('Got SIGHUP signal.');});setTimeout(() => {console.log('Exiting.');  process.exit(0);},100);process.kill(process.pid,'SIGHUP');

WhenSIGUSR1 is received by a Node.js process, Node.js will start thedebugger. SeeSignal Events.

process.loadEnvFile(path)#

Added in: v21.7.0, v20.12.0

Stability: 1.1 - Active development

Loads the.env file intoprocess.env. Usage ofNODE_OPTIONSin the.env file will not have any effect on Node.js.

const { loadEnvFile } =require('node:process');loadEnvFile();import { loadEnvFile }from'node:process';loadEnvFile();

process.mainModule#

Added in: v0.1.17Deprecated since: v14.0.0

Stability: 0 - Deprecated: Userequire.main instead.

Theprocess.mainModule property provides an alternative way of retrievingrequire.main. The difference is that if the main module changes atruntime,require.main may still refer to the original main module inmodules that were required before the change occurred. Generally, it'ssafe to assume that the two refer to the same module.

As withrequire.main,process.mainModule will beundefined if thereis no entry script.

process.memoryUsage()#

History
VersionChanges
v13.9.0, v12.17.0

AddedarrayBuffers to the returned object.

v7.2.0

Addedexternal to the returned object.

v0.1.16

Added in: v0.1.16

Returns an object describing the memory usage of the Node.js process measured inbytes.

import { memoryUsage }from'node:process';console.log(memoryUsage());// Prints:// {//  rss: 4935680,//  heapTotal: 1826816,//  heapUsed: 650472,//  external: 49879,//  arrayBuffers: 9386// }const { memoryUsage } =require('node:process');console.log(memoryUsage());// Prints:// {//  rss: 4935680,//  heapTotal: 1826816,//  heapUsed: 650472,//  external: 49879,//  arrayBuffers: 9386// }
  • heapTotal andheapUsed refer to V8's memory usage.
  • external refers to the memory usage of C++ objects bound to JavaScriptobjects managed by V8.
  • rss, Resident Set Size, is the amount of space occupied in the mainmemory device (that is a subset of the total allocated memory) for theprocess, including all C++ and JavaScript objects and code.
  • arrayBuffers refers to memory allocated forArrayBuffers andSharedArrayBuffers, including all Node.jsBuffers.This is also included in theexternal value. When Node.js is used as anembedded library, this value may be0 because allocations forArrayBuffersmay not be tracked in that case.

When usingWorker threads,rss will be a value that is valid for theentire process, while the other fields will only refer to the current thread.

Theprocess.memoryUsage() method iterates over each page to gatherinformation about memory usage which might be slow depending on theprogram memory allocations.

process.memoryUsage.rss()#

Added in: v15.6.0, v14.18.0

Theprocess.memoryUsage.rss() method returns an integer representing theResident Set Size (RSS) in bytes.

The Resident Set Size, is the amount of space occupied in the mainmemory device (that is a subset of the total allocated memory) for theprocess, including all C++ and JavaScript objects and code.

This is the same value as therss property provided byprocess.memoryUsage()butprocess.memoryUsage.rss() is faster.

import { memoryUsage }from'node:process';console.log(memoryUsage.rss());// 35655680const { memoryUsage } =require('node:process');console.log(memoryUsage.rss());// 35655680

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

History
VersionChanges
v22.7.0, v20.18.0

Changed stability to Legacy.

v18.0.0

Passing an invalid callback to thecallback argument now throwsERR_INVALID_ARG_TYPE instead ofERR_INVALID_CALLBACK.

v1.8.1

Additional arguments aftercallback are now supported.

v0.1.26

Added in: v0.1.26

Stability: 3 - Legacy: UsequeueMicrotask() instead.

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

process.nextTick() addscallback to the "next tick queue". This queue isfully drained after the current operation on the JavaScript stack runs tocompletion and before the event loop is allowed to continue. It's possible tocreate an infinite loop if one were to recursively callprocess.nextTick().See theEvent Loop guide for more background.

import { nextTick }from'node:process';console.log('start');nextTick(() => {console.log('nextTick callback');});console.log('scheduled');// Output:// start// scheduled// nextTick callbackconst { nextTick } =require('node:process');console.log('start');nextTick(() => {console.log('nextTick callback');});console.log('scheduled');// Output:// start// scheduled// nextTick callback

This is important when developing APIs in order to give users the opportunityto assign event handlersafter an object has been constructed but before anyI/O has occurred:

import { nextTick }from'node:process';functionMyThing(options) {this.setupOptions(options);nextTick(() => {this.startDoingStuff();  });}const thing =newMyThing();thing.getReadyForStuff();// thing.startDoingStuff() gets called now, not before.const { nextTick } =require('node:process');functionMyThing(options) {this.setupOptions(options);nextTick(() => {this.startDoingStuff();  });}const thing =newMyThing();thing.getReadyForStuff();// thing.startDoingStuff() gets called now, not before.

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

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

This API is hazardous because in the following case:

const maybeTrue =Math.random() >0.5;maybeSync(maybeTrue,() => {foo();});bar();

It is not clear whetherfoo() orbar() will be called first.

The following approach is much better:

import { nextTick }from'node:process';functiondefinitelyAsync(arg, cb) {if (arg) {nextTick(cb);return;  }  fs.stat('file', cb);}const { nextTick } =require('node:process');functiondefinitelyAsync(arg, cb) {if (arg) {nextTick(cb);return;  }  fs.stat('file', cb);}

When to usequeueMicrotask() vs.process.nextTick()#

ThequeueMicrotask() API is an alternative toprocess.nextTick() that instead of using the"next tick queue" defers execution of a function using the same microtask queue used to execute thethen, catch, and finally handlers of resolved promises.

Within Node.js, every time the "next tick queue" is drained, the microtask queueis drained immediately after.

So in CJS modulesprocess.nextTick() callbacks are always run beforequeueMicrotask() ones.However since ESM modules are processed already as part of the microtask queue, therequeueMicrotask() callbacks are always exectued beforeprocess.nextTick() ones since Node.jsis already in the process of draining the microtask queue.

import { nextTick }from'node:process';Promise.resolve().then(() =>console.log('resolve'));queueMicrotask(() =>console.log('microtask'));nextTick(() =>console.log('nextTick'));// Output:// resolve// microtask// nextTickconst { nextTick } =require('node:process');Promise.resolve().then(() =>console.log('resolve'));queueMicrotask(() =>console.log('microtask'));nextTick(() =>console.log('nextTick'));// Output:// nextTick// resolve// microtask

Formost userland use cases, thequeueMicrotask() API provides a portableand reliable mechanism for deferring execution that works across multipleJavaScript platform environments and should be favored overprocess.nextTick().In simple scenarios,queueMicrotask() can be a drop-in replacement forprocess.nextTick().

console.log('start');queueMicrotask(() => {console.log('microtask callback');});console.log('scheduled');// Output:// start// scheduled// microtask callback

One note-worthy difference between the two APIs is thatprocess.nextTick()allows specifying additional values that will be passed as arguments to thedeferred function when it is called. Achieving the same result withqueueMicrotask() requires using either a closure or a bound function:

functiondeferred(a, b) {console.log('microtask', a + b);}console.log('start');queueMicrotask(deferred.bind(undefined,1,2));console.log('scheduled');// Output:// start// scheduled// microtask 3

There are minor differences in the way errors raised from within the next tickqueue and microtask queue are handled. Errors thrown within a queued microtaskcallback should be handled within the queued callback when possible. If they arenot, theprocess.on('uncaughtException') event handler can be used to captureand handle the errors.

When in doubt, unless the specific capabilities ofprocess.nextTick() areneeded, usequeueMicrotask().

process.noDeprecation#

Added in: v0.8.0

Theprocess.noDeprecation property indicates whether the--no-deprecationflag is set on the current Node.js process. See the documentation forthe'warning' event and theemitWarning() method for more information about thisflag's behavior.

process.permission#

Added in: v20.0.0

This API is available through the--permission flag.

process.permission is an object whose methods are used to manage permissionsfor the current process. Additional documentation is available in thePermission Model.

process.permission.has(scope[, reference])#

Added in: v20.0.0

Verifies that the process is able to access the given scope and reference.If no reference is provided, a global scope is assumed, for instance,process.permission.has('fs.read') will check if the process has ALLfile system read permissions.

The reference has a meaning based on the provided scope. For example,the reference when the scope is File System means files and folders.

The available scopes are:

  • fs - All File System
  • fs.read - File System read operations
  • fs.write - File System write operations
  • child - Child process spawning operations
  • worker - Worker thread spawning operation
// Check if the process has permission to read the README fileprocess.permission.has('fs.read','./README.md');// Check if the process has read permission operationsprocess.permission.has('fs.read');

process.pid#

Added in: v0.1.15

Theprocess.pid property returns the PID of the process.

import { pid }from'node:process';console.log(`This process is pid${pid}`);const { pid } =require('node:process');console.log(`This process is pid${pid}`);

process.platform#

Added in: v0.1.16

Theprocess.platform property returns a string identifying the operatingsystem platform for which the Node.js binary was compiled.

Currently possible values are:

  • 'aix'
  • 'darwin'
  • 'freebsd'
  • 'linux'
  • 'openbsd'
  • 'sunos'
  • 'win32'
import { platform }from'node:process';console.log(`This platform is${platform}`);const { platform } =require('node:process');console.log(`This platform is${platform}`);

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

process.ppid#

Added in: v9.2.0, v8.10.0, v6.13.0

Theprocess.ppid property returns the PID of the parent of thecurrent process.

import { ppid }from'node:process';console.log(`The parent process is pid${ppid}`);const { ppid } =require('node:process');console.log(`The parent process is pid${ppid}`);

process.ref(maybeRefable)#

Added in: v23.6.0, v22.14.0

Stability: 1 - Experimental

  • maybeRefable<any> An object that may be "refable".

An object is "refable" if it implements the Node.js "Refable protocol".Specifically, this means that the object implements theSymbol.for('nodejs.ref')andSymbol.for('nodejs.unref') methods. "Ref'd" objects will keep the Node.jsevent loop alive, while "unref'd" objects will not. Historically, this wasimplemented by usingref() andunref() methods directly on the objects.This pattern, however, is being deprecated in favor of the "Refable protocol"in order to better support Web Platform API types whose APIs cannot be modifiedto addref() andunref() methods but still need to support that behavior.

process.release#

History
VersionChanges
v4.2.0

Thelts property is now supported.

v3.0.0

Added in: v3.0.0

Theprocess.release property returns anObject containing metadata relatedto the current release, including URLs for the source tarball and headers-onlytarball.

process.release contains the following properties:

  • name<string> A value that will always be'node'.
  • sourceUrl<string> an absolute URL pointing to a.tar.gz file containingthe source code of the current release.
  • headersUrl<string> an absolute URL pointing to a.tar.gz file containingonly the source header files for the current release. This file issignificantly smaller than the full source file and can be used for compilingNode.js native add-ons.
  • libUrl<string> |<undefined> an absolute URL pointing to anode.lib filematching the architecture and version of the current release. This file isused for compiling Node.js native add-ons.This property is only present onWindows builds of Node.js and will be missing on all other platforms.
  • lts<string> |<undefined> a string label identifying theLTS label for thisrelease. This property only exists for LTS releases and isundefined for allother release types, includingCurrent releases. Valid values include theLTS Release code names (including those that are no longer supported).
    • 'Fermium' for the 14.x LTS line beginning with 14.15.0.
    • 'Gallium' for the 16.x LTS line beginning with 16.13.0.
    • 'Hydrogen' for the 18.x LTS line beginning with 18.12.0.For other LTS Release code names, seeNode.js Changelog Archive
{name:'node',lts:'Hydrogen',sourceUrl:'https://nodejs.org/download/release/v18.12.0/node-v18.12.0.tar.gz',headersUrl:'https://nodejs.org/download/release/v18.12.0/node-v18.12.0-headers.tar.gz',libUrl:'https://nodejs.org/download/release/v18.12.0/win-x64/node.lib'}

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

process.report#

History
VersionChanges
v13.12.0, v12.17.0

This API is no longer experimental.

v11.8.0

Added in: v11.8.0

process.report is an object whose methods are used to generate diagnosticreports for the current process. Additional documentation is available in thereport documentation.

process.report.compact#

Added in: v13.12.0, v12.17.0

Write reports in a compact format, single-line JSON, more easily consumableby log processing systems than the default multi-line format designed forhuman consumption.

import { report }from'node:process';console.log(`Reports are compact?${report.compact}`);const { report } =require('node:process');console.log(`Reports are compact?${report.compact}`);

process.report.directory#

History
VersionChanges
v13.12.0, v12.17.0

This API is no longer experimental.

v11.12.0

Added in: v11.12.0

Directory where the report is written. The default value is the empty string,indicating that reports are written to the current working directory of theNode.js process.

import { report }from'node:process';console.log(`Report directory is${report.directory}`);const { report } =require('node:process');console.log(`Report directory is${report.directory}`);

process.report.filename#

History
VersionChanges
v13.12.0, v12.17.0

This API is no longer experimental.

v11.12.0

Added in: v11.12.0

Filename where the report is written. If set to the empty string, the outputfilename will be comprised of a timestamp, PID, and sequence number. The defaultvalue is the empty string.

If the value ofprocess.report.filename is set to'stdout' or'stderr',the report is written to the stdout or stderr of the process respectively.

import { report }from'node:process';console.log(`Report filename is${report.filename}`);const { report } =require('node:process');console.log(`Report filename is${report.filename}`);

process.report.getReport([err])#

History
VersionChanges
v13.12.0, v12.17.0

This API is no longer experimental.

v11.8.0

Added in: v11.8.0

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

Returns a JavaScript Object representation of a diagnostic report for therunning process. The report's JavaScript stack trace is taken fromerr, ifpresent.

import { report }from'node:process';import utilfrom'node:util';const data = report.getReport();console.log(data.header.nodejsVersion);// Similar to process.report.writeReport()import fsfrom'node:fs';fs.writeFileSync('my-report.log', util.inspect(data),'utf8');const { report } =require('node:process');const util =require('node:util');const data = report.getReport();console.log(data.header.nodejsVersion);// Similar to process.report.writeReport()const fs =require('node:fs');fs.writeFileSync('my-report.log', util.inspect(data),'utf8');

Additional documentation is available in thereport documentation.

process.report.reportOnFatalError#

History
VersionChanges
v15.0.0, v14.17.0

This API is no longer experimental.

v11.12.0

Added in: v11.12.0

Iftrue, a diagnostic report is generated on fatal errors, such as out ofmemory errors or failed C++ assertions.

import { report }from'node:process';console.log(`Report on fatal error:${report.reportOnFatalError}`);const { report } =require('node:process');console.log(`Report on fatal error:${report.reportOnFatalError}`);

process.report.reportOnSignal#

History
VersionChanges
v13.12.0, v12.17.0

This API is no longer experimental.

v11.12.0

Added in: v11.12.0

Iftrue, a diagnostic report is generated when the process receives thesignal specified byprocess.report.signal.

import { report }from'node:process';console.log(`Report on signal:${report.reportOnSignal}`);const { report } =require('node:process');console.log(`Report on signal:${report.reportOnSignal}`);

process.report.reportOnUncaughtException#

History
VersionChanges
v13.12.0, v12.17.0

This API is no longer experimental.

v11.12.0

Added in: v11.12.0

Iftrue, a diagnostic report is generated on uncaught exception.

import { report }from'node:process';console.log(`Report on exception:${report.reportOnUncaughtException}`);const { report } =require('node:process');console.log(`Report on exception:${report.reportOnUncaughtException}`);

process.report.excludeEnv#

Added in: v23.3.0, v22.13.0

Iftrue, a diagnostic report is generated without the environment variables.

process.report.signal#

History
VersionChanges
v13.12.0, v12.17.0

This API is no longer experimental.

v11.12.0

Added in: v11.12.0

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

import { report }from'node:process';console.log(`Report signal:${report.signal}`);const { report } =require('node:process');console.log(`Report signal:${report.signal}`);

process.report.writeReport([filename][, err])#

History
VersionChanges
v13.12.0, v12.17.0

This API is no longer experimental.

v11.8.0

Added in: v11.8.0

  • filename<string> Name of the file where the report is written. Thisshould be a relative path, that will be appended to the directory specified inprocess.report.directory, or the current working directory of the Node.jsprocess, if unspecified.

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

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

Writes a diagnostic report to a file. Iffilename is not provided, the defaultfilename includes the date, time, PID, and a sequence number. The report'sJavaScript stack trace is taken fromerr, if present.

If the value offilename is set to'stdout' or'stderr', the report iswritten to the stdout or stderr of the process respectively.

import { report }from'node:process';report.writeReport();const { report } =require('node:process');report.writeReport();

Additional documentation is available in thereport documentation.

process.resourceUsage()#

Added in: v12.6.0
  • Returns:<Object> the resource usage for the current process. All of thesevalues come from theuv_getrusage call which returnsauv_rusage_t struct.
    • userCPUTime<integer> maps toru_utime computed in microseconds.It is the same value asprocess.cpuUsage().user.
    • systemCPUTime<integer> maps toru_stime computed in microseconds.It is the same value asprocess.cpuUsage().system.
    • maxRSS<integer> maps toru_maxrss which is the maximum resident setsize used in kilobytes.
    • sharedMemorySize<integer> maps toru_ixrss but is not supported byany platform.
    • unsharedDataSize<integer> maps toru_idrss but is not supported byany platform.
    • unsharedStackSize<integer> maps toru_isrss but is not supported byany platform.
    • minorPageFault<integer> maps toru_minflt which is the number ofminor page faults for the process, seethis article for more details.
    • majorPageFault<integer> maps toru_majflt which is the number ofmajor page faults for the process, seethis article for more details. This field is notsupported on Windows.
    • swappedOut<integer> maps toru_nswap but is not supported by anyplatform.
    • fsRead<integer> maps toru_inblock which is the number of times thefile system had to perform input.
    • fsWrite<integer> maps toru_oublock which is the number of times thefile system had to perform output.
    • ipcSent<integer> maps toru_msgsnd but is not supported by anyplatform.
    • ipcReceived<integer> maps toru_msgrcv but is not supported by anyplatform.
    • signalsCount<integer> maps toru_nsignals but is not supported by anyplatform.
    • voluntaryContextSwitches<integer> maps toru_nvcsw which is thenumber of times a CPU context switch resulted due to a process voluntarilygiving up the processor before its time slice was completed (usually toawait availability of a resource). This field is not supported on Windows.
    • involuntaryContextSwitches<integer> maps toru_nivcsw which is thenumber of times a CPU context switch resulted due to a higher priorityprocess becoming runnable or because the current process exceeded itstime slice. This field is not supported on Windows.
import { resourceUsage }from'node:process';console.log(resourceUsage());/*  Will output:  {    userCPUTime: 82872,    systemCPUTime: 4143,    maxRSS: 33164,    sharedMemorySize: 0,    unsharedDataSize: 0,    unsharedStackSize: 0,    minorPageFault: 2469,    majorPageFault: 0,    swappedOut: 0,    fsRead: 0,    fsWrite: 8,    ipcSent: 0,    ipcReceived: 0,    signalsCount: 0,    voluntaryContextSwitches: 79,    involuntaryContextSwitches: 1  }*/const { resourceUsage } =require('node:process');console.log(resourceUsage());/*  Will output:  {    userCPUTime: 82872,    systemCPUTime: 4143,    maxRSS: 33164,    sharedMemorySize: 0,    unsharedDataSize: 0,    unsharedStackSize: 0,    minorPageFault: 2469,    majorPageFault: 0,    swappedOut: 0,    fsRead: 0,    fsWrite: 8,    ipcSent: 0,    ipcReceived: 0,    signalsCount: 0,    voluntaryContextSwitches: 79,    involuntaryContextSwitches: 1  }*/

process.send(message[, sendHandle[, options]][, callback])#

Added in: v0.5.9
  • message<Object>
  • sendHandle<net.Server> |<net.Socket>
  • options<Object> used to parameterize the sending of certain types ofhandles.options supports the following properties:
    • keepOpen<boolean> A value that can be used when passing instances ofnet.Socket. Whentrue, the socket is kept open in the sending process.Default:false.
  • callback<Function>
  • Returns:<boolean>

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

If Node.js was not spawned with an IPC channel,process.send will beundefined.

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

process.setegid(id)#

Added in: v2.0.0

Theprocess.setegid() method sets the effective group identity of the process.(Seesetegid(2).) Theid can be passed as either a numeric ID or a groupname string. If a group name is specified, this method blocks while resolvingthe associated a numeric ID.

import processfrom'node:process';if (process.getegid && process.setegid) {console.log(`Current gid:${process.getegid()}`);try {    process.setegid(501);console.log(`New gid:${process.getegid()}`);  }catch (err) {console.error(`Failed to set gid:${err}`);  }}const process =require('node:process');if (process.getegid && process.setegid) {console.log(`Current gid:${process.getegid()}`);try {    process.setegid(501);console.log(`New gid:${process.getegid()}`);  }catch (err) {console.error(`Failed to set gid:${err}`);  }}

This function is only available on POSIX platforms (i.e. not Windows orAndroid).This feature is not available inWorker threads.

process.seteuid(id)#

Added in: v2.0.0

Theprocess.seteuid() method sets the effective user identity of the process.(Seeseteuid(2).) Theid can be passed as either a numeric ID or a usernamestring. If a username is specified, the method blocks while resolving theassociated numeric ID.

import processfrom'node:process';if (process.geteuid && process.seteuid) {console.log(`Current uid:${process.geteuid()}`);try {    process.seteuid(501);console.log(`New uid:${process.geteuid()}`);  }catch (err) {console.error(`Failed to set uid:${err}`);  }}const process =require('node:process');if (process.geteuid && process.seteuid) {console.log(`Current uid:${process.geteuid()}`);try {    process.seteuid(501);console.log(`New uid:${process.geteuid()}`);  }catch (err) {console.error(`Failed to set uid:${err}`);  }}

This function is only available on POSIX platforms (i.e. not Windows orAndroid).This feature is not available inWorker threads.

process.setgid(id)#

Added in: v0.1.31

Theprocess.setgid() method sets the group identity of the process. (Seesetgid(2).) Theid can be passed as either a numeric ID or a group namestring. If a group name is specified, this method blocks while resolving theassociated numeric ID.

import processfrom'node:process';if (process.getgid && process.setgid) {console.log(`Current gid:${process.getgid()}`);try {    process.setgid(501);console.log(`New gid:${process.getgid()}`);  }catch (err) {console.error(`Failed to set gid:${err}`);  }}const process =require('node:process');if (process.getgid && process.setgid) {console.log(`Current gid:${process.getgid()}`);try {    process.setgid(501);console.log(`New gid:${process.getgid()}`);  }catch (err) {console.error(`Failed to set gid:${err}`);  }}

This function is only available on POSIX platforms (i.e. not Windows orAndroid).This feature is not available inWorker threads.

process.setgroups(groups)#

Added in: v0.9.4

Theprocess.setgroups() method sets the supplementary group IDs for theNode.js process. This is a privileged operation that requires the Node.jsprocess to haveroot or theCAP_SETGID capability.

Thegroups array can contain numeric group IDs, group names, or both.

import processfrom'node:process';if (process.getgroups && process.setgroups) {try {    process.setgroups([501]);console.log(process.getgroups());// new groups  }catch (err) {console.error(`Failed to set groups:${err}`);  }}const process =require('node:process');if (process.getgroups && process.setgroups) {try {    process.setgroups([501]);console.log(process.getgroups());// new groups  }catch (err) {console.error(`Failed to set groups:${err}`);  }}

This function is only available on POSIX platforms (i.e. not Windows orAndroid).This feature is not available inWorker threads.

process.setuid(id)#

Added in: v0.1.28

Theprocess.setuid(id) method sets the user identity of the process. (Seesetuid(2).) Theid can be passed as either a numeric ID or a username string.If a username is specified, the method blocks while resolving the associatednumeric ID.

import processfrom'node:process';if (process.getuid && process.setuid) {console.log(`Current uid:${process.getuid()}`);try {    process.setuid(501);console.log(`New uid:${process.getuid()}`);  }catch (err) {console.error(`Failed to set uid:${err}`);  }}const process =require('node:process');if (process.getuid && process.setuid) {console.log(`Current uid:${process.getuid()}`);try {    process.setuid(501);console.log(`New uid:${process.getuid()}`);  }catch (err) {console.error(`Failed to set uid:${err}`);  }}

This function is only available on POSIX platforms (i.e. not Windows orAndroid).This feature is not available inWorker threads.

process.setSourceMapsEnabled(val)#

Added in: v16.6.0, v14.18.0

Stability: 1 - Experimental: Usemodule.setSourceMapsSupport() instead.

This function enables or disables theSource Map support forstack traces.

It provides same features as launching Node.js process with commandline options--enable-source-maps.

Only source maps in JavaScript files that are loaded after source maps has beenenabled will be parsed and loaded.

This implies callingmodule.setSourceMapsSupport() with an option{ nodeModules: true, generatedCode: true }.

process.setUncaughtExceptionCaptureCallback(fn)#

Added in: v9.3.0

Theprocess.setUncaughtExceptionCaptureCallback() function sets a functionthat will be invoked when an uncaught exception occurs, which will receive theexception value itself as its first argument.

If such a function is set, the'uncaughtException' event willnot be emitted. If--abort-on-uncaught-exception was passed from thecommand line or set throughv8.setFlagsFromString(), the process willnot abort. Actions configured to take place on exceptions such as reportgenerations will be affected too

To unset the capture function,process.setUncaughtExceptionCaptureCallback(null) may be used. Calling thismethod with a non-null argument while another capture function is set willthrow an error.

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

process.sourceMapsEnabled#

Added in: v20.7.0, v18.19.0

Stability: 1 - Experimental: Usemodule.getSourceMapsSupport() instead.

Theprocess.sourceMapsEnabled property returns whether theSource Map support for stack traces is enabled.

process.stderr#

Theprocess.stderr property returns a stream connected tostderr (fd2). It is anet.Socket (which is aDuplexstream) unless fd2 refers to a file, in which case it isaWritable stream.

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

process.stderr.fd#

This property refers to the value of underlying file descriptor ofprocess.stderr. The value is fixed at2. InWorker threads,this field does not exist.

process.stdin#

Theprocess.stdin property returns a stream connected tostdin (fd0). It is anet.Socket (which is aDuplexstream) unless fd0 refers to a file, in which case it isaReadable stream.

For details of how to read fromstdin seereadable.read().

As aDuplex stream,process.stdin can also be used in "old" mode thatis compatible with scripts written for Node.js prior to v0.10.For more information seeStream compatibility.

In "old" streams mode thestdin stream is paused by default, so onemust callprocess.stdin.resume() to read from it. Note also that callingprocess.stdin.resume() itself would switch stream to "old" mode.

process.stdin.fd#

This property refers to the value of underlying file descriptor ofprocess.stdin. The value is fixed at0. InWorker threads,this field does not exist.

process.stdout#

Theprocess.stdout property returns a stream connected tostdout (fd1). It is anet.Socket (which is aDuplexstream) unless fd1 refers to a file, in which case it isaWritable stream.

For example, to copyprocess.stdin toprocess.stdout:

import { stdin, stdout }from'node:process';stdin.pipe(stdout);const { stdin, stdout } =require('node:process');stdin.pipe(stdout);

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

process.stdout.fd#

This property refers to the value of underlying file descriptor ofprocess.stdout. The value is fixed at1. InWorker threads,this field does not exist.

A note on process I/O#

process.stdout andprocess.stderr differ from other Node.js streams inimportant ways:

  1. They are used internally byconsole.log() andconsole.error(),respectively.
  2. Writes may be synchronous depending on what the stream is connected toand whether the system is Windows or POSIX:
    • Files:synchronous on Windows and POSIX
    • TTYs (Terminals):asynchronous on Windows,synchronous on POSIX
    • Pipes (and sockets):synchronous on Windows,asynchronous on POSIX

These behaviors are partly for historical reasons, as changing them wouldcreate backward incompatibility, but they are also expected by some users.

Synchronous writes avoid problems such as output written withconsole.log() orconsole.error() being unexpectedly interleaved, or not written at all ifprocess.exit() is called before an asynchronous write completes. Seeprocess.exit() for more information.

Warning: Synchronous writes block the event loop until the write hascompleted. This can be near instantaneous in the case of output to a file, butunder high system load, pipes that are not being read at the receiving end, orwith slow terminals or file systems, it's possible for the event loop to beblocked often enough and long enough to have severe negative performanceimpacts. This may not be a problem when writing to an interactive terminalsession, but consider this particularly careful when doing production logging tothe process output streams.

To check if a stream is connected to aTTY context, check theisTTYproperty.

For instance:

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

See theTTY documentation for more information.

process.throwDeprecation#

Added in: v0.9.12

The initial value ofprocess.throwDeprecation indicates whether the--throw-deprecation flag is set on the current Node.js process.process.throwDeprecation is mutable, so whether or not deprecationwarnings result in errors may be altered at runtime. See thedocumentation for the'warning' event and theemitWarning() method for more information.

$node --throw-deprecation -p"process.throwDeprecation"true$node -p"process.throwDeprecation"undefined$node>process.emitWarning('test','DeprecationWarning');undefined>(node:26598) DeprecationWarning:test>process.throwDeprecation =true;true>process.emitWarning('test','DeprecationWarning');Thrown:[DeprecationWarning: test] { name: 'DeprecationWarning' }

process.threadCpuUsage([previousValue])#

Added in: v23.9.0

Theprocess.threadCpuUsage() method returns the user and system CPU time usage ofthe current worker thread, in an object with propertiesuser andsystem, whosevalues are microsecond values (millionth of a second).

The result of a previous call toprocess.threadCpuUsage() can be passed as theargument to the function, to get a diff reading.

process.title#

Added in: v0.1.104

Theprocess.title property returns the current process title (i.e. returnsthe current value ofps). Assigning a new value toprocess.title modifiesthe current value ofps.

When a new value is assigned, different platforms will impose different maximumlength restrictions on the title. Usually such restrictions are quite limited.For instance, on Linux and macOS,process.title is limited to the size of thebinary name plus the length of the command-line arguments because setting theprocess.title overwrites theargv memory of the process. Node.js v0.8allowed for longer process title strings by also overwriting theenvironmemory but that was potentially insecure and confusing in some (rather obscure)cases.

Assigning a value toprocess.title might not result in an accurate labelwithin process manager applications such as macOS Activity Monitor or WindowsServices Manager.

process.traceDeprecation#

Added in: v0.8.0

Theprocess.traceDeprecation property indicates whether the--trace-deprecation flag is set on the current Node.js process. See thedocumentation for the'warning' event and theemitWarning() method for more information about thisflag's behavior.

process.umask()#

History
VersionChanges
v14.0.0, v12.19.0

Callingprocess.umask() with no arguments is deprecated.

v0.1.19

Added in: v0.1.19

Stability: 0 - Deprecated. Callingprocess.umask() with no argument causesthe process-wide umask to be written twice. This introduces a race conditionbetween threads, and is a potential security vulnerability. There is no safe,cross-platform alternative API.

process.umask() returns the Node.js process's file mode creation mask. Childprocesses inherit the mask from the parent process.

process.umask(mask)#

Added in: v0.1.19

process.umask(mask) sets the Node.js process's file mode creation mask. Childprocesses inherit the mask from the parent process. Returns the previous mask.

import { umask }from'node:process';const newmask =0o022;const oldmask =umask(newmask);console.log(`Changed umask from${oldmask.toString(8)} to${newmask.toString(8)}`,);const { umask } =require('node:process');const newmask =0o022;const oldmask =umask(newmask);console.log(`Changed umask from${oldmask.toString(8)} to${newmask.toString(8)}`,);

InWorker threads,process.umask(mask) will throw an exception.

process.unref(maybeRefable)#

Added in: v23.6.0, v22.14.0

Stability: 1 - Experimental

  • maybeUnfefable<any> An object that may be "unref'd".

An object is "unrefable" if it implements the Node.js "Refable protocol".Specifically, this means that the object implements theSymbol.for('nodejs.ref')andSymbol.for('nodejs.unref') methods. "Ref'd" objects will keep the Node.jsevent loop alive, while "unref'd" objects will not. Historically, this wasimplemented by usingref() andunref() methods directly on the objects.This pattern, however, is being deprecated in favor of the "Refable protocol"in order to better support Web Platform API types whose APIs cannot be modifiedto addref() andunref() methods but still need to support that behavior.

process.uptime()#

Added in: v0.5.0

Theprocess.uptime() method returns the number of seconds the current Node.jsprocess has been running.

The return value includes fractions of a second. UseMath.floor() to get wholeseconds.

process.version#

Added in: v0.1.3

Theprocess.version property contains the Node.js version string.

import { version }from'node:process';console.log(`Version:${version}`);// Version: v14.8.0const { version } =require('node:process');console.log(`Version:${version}`);// Version: v14.8.0

To get the version string without the prependedv, useprocess.versions.node.

process.versions#

History
VersionChanges
v9.0.0

Thev8 property now includes a Node.js specific suffix.

v4.2.0

Theicu property is now supported.

v0.2.0

Added in: v0.2.0

Theprocess.versions property returns an object listing the version strings ofNode.js and its dependencies.process.versions.modules indicates the currentABI version, which is increased whenever a C++ API changes. Node.js will refuseto load modules that were compiled against a different module ABI version.

import { versions }from'node:process';console.log(versions);const { versions } =require('node:process');console.log(versions);

Will generate an object similar to:

{ node: '23.0.0',  acorn: '8.11.3',  ada: '2.7.8',  ares: '1.28.1',  base64: '0.5.2',  brotli: '1.1.0',  cjs_module_lexer: '1.2.2',  cldr: '45.0',  icu: '75.1',  llhttp: '9.2.1',  modules: '127',  napi: '9',  nghttp2: '1.61.0',  nghttp3: '0.7.0',  ngtcp2: '1.3.0',  openssl: '3.0.13+quic',  simdjson: '3.8.0',  simdutf: '5.2.4',  sqlite: '3.46.0',  tz: '2024a',  undici: '6.13.0',  unicode: '15.1',  uv: '1.48.0',  uvwasi: '0.0.20',  v8: '12.4.254.14-node.11',  zlib: '1.3.0.1-motley-7d77fb7' }

Exit codes#

Node.js will normally exit with a0 status code when no more asyncoperations are pending. The following status codes are used in othercases:

  • 1Uncaught Fatal Exception: There was an uncaught exception,and it was not handled by a domain or an'uncaughtException' eventhandler.
  • 2: Unused (reserved by Bash for builtin misuse)
  • 3Internal JavaScript Parse Error: The JavaScript source codeinternal in the Node.js bootstrapping process caused a parse error. Thisis extremely rare, and generally can only happen during developmentof Node.js itself.
  • 4Internal JavaScript Evaluation Failure: The JavaScriptsource code internal in the Node.js bootstrapping process failed toreturn a function value when evaluated. This is extremely rare, andgenerally can only happen during development of Node.js itself.
  • 5Fatal Error: There was a fatal unrecoverable error in V8.Typically a message will be printed to stderr with the prefixFATAL ERROR.
  • 6Non-function Internal Exception Handler: There was anuncaught exception, but the internal fatal exception handlerfunction was somehow set to a non-function, and could not be called.
  • 7Internal Exception Handler Run-Time Failure: There was anuncaught exception, and the internal fatal exception handlerfunction itself threw an error while attempting to handle it. Thiscan happen, for example, if an'uncaughtException' ordomain.on('error') handler throws an error.
  • 8: Unused. In previous versions of Node.js, exit code 8 sometimesindicated an uncaught exception.
  • 9Invalid Argument: Either an unknown option was specified,or an option requiring a value was provided without a value.
  • 10Internal JavaScript Run-Time Failure: The JavaScriptsource code internal in the Node.js bootstrapping process threw an errorwhen the bootstrapping function was called. This is extremely rare,and generally can only happen during development of Node.js itself.
  • 12Invalid Debug Argument: The--inspect and/or--inspect-brkoptions were set, but the port number chosen was invalid or unavailable.
  • 13Unsettled Top-Level Await:await was used outside of a functionin the top-level code, but the passedPromise never settled.
  • 14Snapshot Failure: Node.js was started to build a V8 startupsnapshot and it failed because certain requirements of the state ofthe application were not met.
  • >128Signal Exits: If Node.js receives a fatal signal such asSIGKILL orSIGHUP, then its exit code will be128 plus thevalue of the signal code. This is a standard POSIX practice, sinceexit codes are defined to be 7-bit integers, and signal exits setthe high-order bit, and then contain the value of the signal code.For example, signalSIGABRT has value6, so the expected exitcode will be128 +6, or134.