Skip to main content

Process

Stability: 2 - Stable
The process object provides information about, and control over, the current Node.js process.
import process from 'node:process';
// or
const process = require('node:process');

Process Events

The process object is an instance of EventEmitter.

Event: ‘beforeExit’

Added in: v0.11.12
The ‘beforeExit’ event is emitted when Node.js empties its event loop and has no additional work to schedule. Normally, the Node.js process will exit when there is no work scheduled, but a listener registered on the ‘beforeExit’ event can make asynchronous calls, and thereby cause the Node.js process to continue.
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.');

Event: ‘exit’

Added in: v0.1.7
code
integer
required
The exit code
The ‘exit’ event is emitted when the Node.js process is about to exit as a result of either:
  • The process.exit() method being called explicitly
  • The Node.js event loop no longer having any additional work to perform
process.on('exit', (code) => {
  console.log(`About to exit with code: ${code}`);
});
Listener functions MUST only perform synchronous operations. The Node.js process will exit immediately after calling the ‘exit’ event listeners causing any additional work still queued in the event loop to be abandoned.

Event: ‘uncaughtException’

Added in: v0.1.18
err
Error
required
The uncaught exception
origin
string
required
Indicates if the exception originates from an unhandled rejection or from a synchronous error. Can either be ‘uncaughtException’ or ‘unhandledRejection’.
The ‘uncaughtException’ event is emitted when an uncaught JavaScript exception bubbles all the way back to the event loop.
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.');
‘uncaughtException’ is a crude mechanism for exception handling intended to be used only as a last resort. The event should not be used as an equivalent to On Error Resume Next. The correct use of ‘uncaughtException’ is to perform synchronous cleanup of allocated resources before shutting down the process.

Event: ‘unhandledRejection’

Added in: v1.4.1
reason
Error | any
required
The object with which the promise was rejected (typically an Error object)
promise
Promise
required
The rejected promise
The ‘unhandledRejection’ event is emitted whenever a Promise is rejected and no error handler is attached to the promise within a turn of the event loop.
process.on('unhandledRejection', (reason, promise) => {
  console.log('Unhandled Rejection at:', promise, 'reason:', reason);
});

somePromise.then((res) => {
  return reportToUser(JSON.pasre(res)); // Note the typo
}); // No .catch() or .then()

Event: ‘warning’

Added in: v6.0.0
warning
Error
required
The warning details including name, message, and stack properties
The ‘warning’ event is emitted whenever Node.js emits a process warning.
process.on('warning', (warning) => {
  console.warn(warning.name);    // Print the warning name
  console.warn(warning.message); // Print the warning message
  console.warn(warning.stack);   // Print the stack trace
});

Process Properties

process.arch

Added in: v0.5.0
arch
string
The operating system CPU architecture for which the Node.js binary was compiled. Possible values: ‘arm’, ‘arm64’, ‘ia32’, ‘loong64’, ‘mips’, ‘mipsel’, ‘ppc64’, ‘riscv64’, ‘s390’, ‘s390x’, ‘x64’.
console.log(`This processor architecture is ${process.arch}`);

process.argv

Added in: v0.1.27
argv
string[]
An array containing the command-line arguments passed when the Node.js process was launched.
The first element will be process.execPath. The second element will be the path to the JavaScript file being executed. The remaining elements will be any additional command-line arguments.
// print process.argv
process.argv.forEach((val, index) => {
  console.log(`${index}: ${val}`);
});

process.argv0

Added in: v6.4.0
argv0
string
A read-only copy of the original value of argv[0] passed when Node.js starts.

process.env

Added in: v0.1.27
env
Object
An object containing the user environment.
{
  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',
  HOME: '/Users/maciej',
  LOGNAME: 'maciej',
}
It is possible to modify this object, but such modifications will not be reflected outside the Node.js process.
process.env.foo = 'bar';
console.log(process.env.foo); // 'bar'

process.execPath

Added in: v0.1.100
execPath
string
The absolute pathname of the executable that started the Node.js process.
console.log(process.execPath);
// '/usr/local/bin/node'

process.exitCode

Added in: v0.11.8
exitCode
integer | undefined
A number which will be the process exit code when the process either exits gracefully, or is exited via process.exit() without specifying a code.
process.exitCode = 1;

process.pid

Added in: v0.1.15
pid
integer
The PID of the process.
console.log(`This process is pid ${process.pid}`);

process.platform

Added in: v0.1.16
platform
string
The operating system platform on which the Node.js process is running. Possible values: ‘aix’, ‘darwin’, ‘freebsd’, ‘linux’, ‘openbsd’, ‘sunos’, ‘win32’.
console.log(`This platform is ${process.platform}`);

process.version

Added in: v0.1.3
version
string
The Node.js version string.
console.log(`Version: ${process.version}`);
// Version: v18.12.0

process.versions

Added in: v0.2.0
versions
Object
An object listing the version strings of Node.js and its dependencies.
console.log(process.versions);
// {
//   node: '18.12.0',
//   v8: '10.2.154.15-node.12',
//   uv: '1.43.0',
//   zlib: '1.2.11',
//   ...
// }

Process Methods

process.abort()

Added in: v0.7.0
The process.abort() method causes the Node.js process to exit immediately and generate a core file.
This feature is not available in Worker threads.

process.chdir(directory)

Added in: v0.1.17
directory
string
required
The new working directory path
The process.chdir() method changes the current working directory of the Node.js process or throws an exception if doing so fails.
console.log(`Starting directory: ${process.cwd()}`);
try {
  process.chdir('/tmp');
  console.log(`New directory: ${process.cwd()}`);
} catch (err) {
  console.error(`chdir: ${err}`);
}

process.cwd()

Added in: v0.1.8
return
string
The current working directory of the Node.js process.
console.log(`Current directory: ${process.cwd()}`);

process.exit([code])

Added in: v0.1.13
code
integer | string | null | undefined
default:"0"
The exit code. For string type, only integer strings are allowed.
The process.exit() method instructs Node.js to terminate the process synchronously with an exit status of code.
process.exit(1);
Calling process.exit() will force the process to exit as quickly as possible even if there are still asynchronous operations pending.

process.kill(pid[, signal])

Added in: v0.0.6
pid
number
required
A process ID
signal
string | number
default:"'SIGTERM'"
The signal to send, either as a string or number
The process.kill() method sends the signal to the process identified by pid.
process.on('SIGHUP', () => {
  console.log('Got SIGHUP signal.');
});

setTimeout(() => {
  console.log('Exiting.');
  process.exit(0);
}, 100);

process.kill(process.pid, 'SIGHUP');

process.memoryUsage()

Added in: v0.1.16
return
Object
Returns an object describing the memory usage of the Node.js process measured in bytes.
console.log(process.memoryUsage());
// {
//   rss: 4935680,
//   heapTotal: 1826816,
//   heapUsed: 650472,
//   external: 49879,
//   arrayBuffers: 9386
// }

process.nextTick(callback[, …args])

Added in: v0.1.26
callback
Function
required
The callback function
...args
any
Additional arguments to pass to the callback
process.nextTick() adds callback to the “next tick queue”. This queue is fully drained after the current operation on the JavaScript stack runs to completion and before the event loop is allowed to continue.
console.log('start');
process.nextTick(() => {
  console.log('nextTick callback');
});
console.log('scheduled');
// Output:
// start
// scheduled
// nextTick callback

process.uptime()

Added in: v0.5.0
return
number
The number of seconds the current Node.js process has been running.
console.log(`Uptime: ${process.uptime()} seconds`);

Standard Streams

process.stdin

Added in: v0.1.104
stdin
stream.Readable
A Readable Stream representing standard input (fd 0).
process.stdin.setEncoding('utf8');

process.stdin.on('readable', () => {
  let chunk;
  while ((chunk = process.stdin.read()) !== null) {
    process.stdout.write(`data: ${chunk}`);
  }
});

process.stdin.on('end', () => {
  process.stdout.write('end');
});

process.stdout

Added in: v0.1.104
stdout
stream.Writable
A Writable Stream to stdout (fd 1).
process.stdout.write('hello world!');

process.stderr

Added in: v0.1.104
stderr
stream.Writable
A Writable Stream to stderr (fd 2).
process.stderr.write('This is an error message\n');

Signal Events

Signal events will be emitted when the Node.js process receives a signal. Please refer to signal(7) for a listing of standard POSIX signal names such as ‘SIGINT’, ‘SIGHUP’, etc.
process.stdin.resume();

process.on('SIGINT', () => {
  console.log('Received SIGINT. Press Control-D to exit.');
});

// Using a single function to handle multiple signals
function handle(signal) {
  console.log(`Received ${signal}`);
}

process.on('SIGINT', handle);
process.on('SIGTERM', handle);