process
The process object is a global available in all Node.js applications. It provides information about the current process and offers methods to control it. Unlike most modules that require an explicit import, process is available everywhere—you can access environment variables, command-line arguments, and termination methods directly.
This object is an instance of EventEmitter, so you can listen to process-level events like 'exit', 'uncaughtException', and 'SIGINT'.
Command-Line Arguments
process.argv
An array containing the command-line arguments passed when the Node.js process was launched. The first element is the path to the Node.js executable, the second is the path to the script being run, and the remaining elements are any additional arguments.
// Running: node app.js --version 1.0
console.log(process.argv);
// ['/usr/local/bin/node', '/path/to/app.js', '--version', '1.0']
process.argv0
A read-only copy of the original argv[0] value. This is useful when you need the exact value passed at startup, since process.argv[0] can be modified by the script.
console.log(process.argv0);
// 'node' or whatever argv[0] was originally set to
process.execPath
The absolute path to the Node.js executable that started the process.
console.log(process.execPath);
// '/usr/local/bin/node' on macOS/Linux
// 'C:\\Program Files\\nodejs\\node.exe' on Windows
Environment Information
process.env
An object containing user environment variables. You can read and write to this object to modify environment variables for the current process.
// Read an environment variable
console.log(process.env.NODE_ENV);
// 'development' or 'production'
// Set a custom environment variable
process.env.MY_APP_SECRET = 'secret-key';
This property is particularly useful for configuring application behavior based on the environment. For example, you might enable verbose logging only when NODE_ENV !== 'production'.
process.platform
The operating system platform where the Node.js process is running.
console.log(process.platform);
// 'linux', 'darwin', 'win32', 'freebsd', 'openbsd'
process.arch
The CPU architecture of the Node.js binary.
console.log(process.arch);
// 'x64', 'arm64', 'arm', 'ia32', 's390', etc.
process.version
The Node.js version string.
console.log(process.version);
// 'v22.10.0'
process.versions
An object containing version information for Node.js and its dependencies.
console.log(process.versions);
// {
// node: '22.10.0',
// v8: '12.8.344.25-node.6',
// uv: '1.120.0',
// zlib: '1.3.1',
// openssl: '3.0.15',
// ...
// }
Process Identification
process.pid
The process ID of the current process.
console.log(process.pid);
// 12345
process.ppid
The process ID of the parent process.
console.log(process.ppid);
// 67890
Working Directory
process.cwd()
Returns the current working directory of the Node.js process.
console.log(process.cwd());
// '/home/user/project'
process.chdir(directory)
Changes the current working directory of the process. Throws an error if the directory doesn’t exist or isn’t accessible.
console.log(`Starting directory: ${process.cwd()}`);
try {
process.chdir('/tmp');
console.log(`New directory: ${process.cwd()}`);
} catch (err) {
console.error(`Failed to change directory: ${err}`);
}
Exiting and Terminating
process.exit([code])
Terminates the process with the specified exit code. Omitting the code or passing 0 indicates successful termination. Passing a non-zero value indicates error conditions.
// Exit with success code
process.exit(0);
// Exit with error code
process.exit(1);
// Exit with custom error code
process.exit(42);
process.exitCode
A number that can be set to specify the exit code when the process exits naturally (without calling process.exit() explicitly).
process.exitCode = 1;
// When the process exits naturally, it will use code 1
process.abort()
Causes the Node.js process to exit immediately and generate a core dump. This is useful for debugging but should be avoided in production code.
process.abort();
// Generates a core file and terminates
process.kill(pid[, signal])
Sends a signal to another process. By default, this sends SIGTERM.
// Send SIGTERM to a process
process.kill(12345);
// Send a specific signal
process.kill(12345, 'SIGKILL');
// Send signal 0 to check if process exists (doesn't actually kill it)
try {
process.kill(12345, 0);
console.log('Process exists');
} catch (err) {
console.log('Process does not exist');
}
Memory and CPU Usage
process.memoryUsage()
Returns an object describing memory usage of the Node.js process.
console.log(process.memoryUsage());
// {
// rss: 25645056,
// heapTotal: 4894712,
// heapUsed: 2763656,
// external: 245760,
// arrayBuffers: 11936
// }
rss(Resident Set Size): Total memory allocated by the processheapTotalandheapUsed: V8 heap memoryexternal: Memory used by native addons
process.cpuUsage([previousValue])
Returns CPU usage for the current process. You can pass a previous value to get a delta.
const start = process.cpuUsage();
// { user: 1000, system: 500 }
// ... your code runs here ...
const end = process.cpuUsage(start);
// { user: 2500, system: 800 }
process.resourceUsage()
Returns resource usage for the current process, including filesystem I/O and network socket counts.
console.log(process.resourceUsage());
// {
// userCPUUsage: 12345,
// systemCPUUsage: 6789,
// maxRSS: 45678,
// sharedMemorySize: -1,
// ...
// }
Time and Timing
process.uptime()
Returns the number of seconds the current Node.js process has been running.
console.log(`Process uptime: ${process.uptime()} seconds`);
// Process uptime: 3600 seconds
process.hrtime([time])
Returns the current high-resolution real time as a tuple [seconds, nanoseconds]. Pass a previous value to get a diff.
const start = process.hrtime();
// ... code being timed ...
const diff = process.hrtime(start);
console.log(`Took ${diff[0] * 1000 + diff[1] / 1000000} milliseconds`);
process.nextTick(callback)
Invokes the callback after the current operation completes but before the event loop continues. This has higher priority than other I/O events.
console.log('Start');
process.nextTick(() => {
console.log('Next tick');
});
console.log('End');
// Output: Start, End, Next tick
Error Handling Events
The process object emits several events related to error handling:
'uncaughtException': Emitted when an uncaught exception bubbles up to the event loop'unhandledRejection': Emitted when a Promise is rejected but has no handler'rejectionHandled': Emitted when a previously unhandled rejection gets a handler later'exit': Emitted when the process is about to exit
process.on('uncaughtException', (err, origin) => {
console.error(`Uncaught exception: ${err.message}`);
process.exit(1);
});
process.on('unhandledRejection', (reason, promise) => {
console.error(`Unhandled rejection at: ${promise}, reason: ${reason}`);
});
Standard Streams
process.stdin, process.stdout, process.stderr
Standard input, output, and error streams. These are Stream objects that can be used for reading input or writing output.
// Reading from stdin
process.stdin.setEncoding('utf8');
process.stdin.on('data', (chunk) => {
console.log(`Received: ${chunk}`);
});
// Writing to stdout
process.stdout.write('Hello, world!\n');
// Writing to stderr
process.stderr.write('Error occurred!\n');
Process Events
Signal Events
The process emits events when it receives OS signals:
// Handle SIGINT (Ctrl+C)
process.on('SIGINT', () => {
console.log('Received SIGINT, shutting down gracefully');
process.exit(0);
});
// Handle SIGTERM
process.on('SIGTERM', () => {
console.log('Received SIGTERM, shutting down');
process.exit(0);
});
Common signals:
SIGINT: Interrupt from terminal (Ctrl+C)SIGTERM: Termination requestSIGKILL: Immediate termination (cannot be caught)
Common Patterns
Graceful Shutdown
process.on('SIGTERM', shutdown);
process.on('SIGINT', shutdown);
function shutdown() {
console.log('Shutting down...');
// Clean up resources
process.exit(0);
}
Environment-Based Configuration
const isProduction = process.env.NODE_ENV === 'production';
if (isProduction) {
console.log('Running in production mode');
} else {
console.log('Running in development mode');
}
Measuring Execution Time
const start = process.hrtime.bigint();
// Your code here
const result = heavyComputation();
const end = process.hrtime.bigint();
console.log(`Execution took ${(end - start) / 1000000n}ms`);