process
Node.js's 'process' is a global object that lets you retrieve information about and interact with the running Node.js process. It can be used anywhere without require().
Main Properties and Methods
| Property / Method | Description |
|---|---|
process.argv | Returns command-line arguments as an array. |
process.env | Returns environment variables as an object. |
process.cwd() | Returns the absolute path of the current working directory. |
process.exit() | Terminates the Node.js process. An exit code can be specified as an argument. |
process.pid | Returns the current process ID as a number. |
process.ppid | Returns the parent process ID as a number. |
process.platform | Returns the OS name of the runtime environment ('linux', 'darwin', 'win32', etc.). |
process.version | Returns the Node.js version as a string (e.g., 'v20.11.0'). |
process.versions | Returns the versions of Node.js and its dependencies as an object. |
process.stdin | The standard input ReadableStream. |
process.stdout | The standard output WritableStream. |
process.stderr | The standard error output WritableStream. |
process.memoryUsage() | Returns the process memory usage as an object in bytes. |
process.uptime() | Returns the elapsed time in seconds since the process started. |
process.hrtime() | Returns high-resolution elapsed time as an array of [seconds, nanoseconds]. |
process.nextTick(fn) | Executes a callback immediately after the current event loop completes. |
process.on(event, fn) | Registers a listener for process events ('exit', 'uncaughtException', etc.). |
process.argv — Getting Command-Line Arguments
process.argv is an array where index 0 is the Node.js executable path and index 1 is the script file path. Arguments passed by the user are stored at index 2 and beyond.
argv.js
// Check command-line arguments
console.log('All args:', process.argv);
// User-passed arguments start at index 2
var args = process.argv.slice(2);
console.log('User args:', args);
// Use default values if no arguments provided
var name = args[0] || 'Okabe Rintaro';
var target = args[1] || 'the future';
console.log('Sending D-Mail from ' + name + ' to ' + target);
node argv.js "Makise Kurisu" "the past" All args: [ '/usr/local/bin/node', '/home/okabe/argv.js', 'Makise Kurisu', 'the past' ] User args: [ 'Makise Kurisu', 'the past' ] Sending D-Mail from Makise Kurisu to the past
process.env — Accessing Environment Variables
Environment variables are accessed as properties of an object. Keys that do not exist return undefined, so they are commonly used with default values. See the process.env (environment variables) page for details.
env.js
// Get environment variables (use defaults if not set)
var host = process.env.HOST || 'localhost';
var port = process.env.PORT || '3000';
var mode = process.env.NODE_ENV || 'development';
console.log('Host:', host);
console.log('Port:', port);
console.log('Mode:', mode);
node env.js Host: localhost Port: 3000 Mode: development
process.cwd() and process.exit()
cwd_exit.js
// Get the current working directory
console.log('Current directory:', process.cwd());
// Check if a required file exists; exit with error if not found
var fs = require('fs');
var configPath = process.cwd() + '/config.json';
if (!fs.existsSync(configPath)) {
// Write a message to standard error
process.stderr.write('Error: config.json not found\n');
// Exit with code 1 (abnormal exit)
// 0 = normal exit, 1 or higher = abnormal exit (detectable in shell scripts)
process.exit(1);
}
console.log('Configuration file loaded');
process.exit(0); // Normal exit
node cwd_exit.js Current directory: /home/okabe/future-gadget-lab Error: config.json not found
process.pid and process.platform
process_info.js
// Display basic process information
console.log('Process ID:', process.pid);
console.log('Parent PID:', process.ppid);
console.log('OS:', process.platform);
console.log('Node.js version:', process.version);
console.log('Uptime:', process.uptime().toFixed(2) + 's');
// Branch based on OS
if (process.platform === 'win32') {
console.log('Shiina Mayuri: Running on Windows~!');
} else {
console.log('Hashida Itaru: Running on a Unix-based OS');
}
node process_info.js Process ID: 12345 Parent PID: 12300 OS: linux Node.js version: v20.11.0 Uptime: 0.05s Hashida Itaru: Running on a Unix-based OS
process.stdin — Reading Standard Input
stdin.js
// Read data from standard input
// Set character encoding to UTF-8
process.stdin.setEncoding('utf8');
process.stdout.write('Enter the time machine destination: ');
// The 'data' event fires each time data is entered
process.stdin.on('data', function(input) {
// Remove trailing newline
var destination = input.trim();
console.log('Amane Suzuha: Heading to ' + destination + '. El Psy Kongroo');
// Stop reading input
process.stdin.pause();
});
node stdin.js Enter the time machine destination: 1975 Amane Suzuha: Heading to 1975. El Psy Kongroo
Sample Code — Displaying Process Info in One Go
process_report.js
// A report that displays process status all at once
function printReport() {
var mem = process.memoryUsage();
console.log('=== Future Gadget Lab Process Report ===');
console.log('PID :', process.pid);
console.log('Platform :', process.platform);
console.log('Node.js :', process.version);
console.log('CWD :', process.cwd());
console.log('Uptime :', process.uptime().toFixed(3) + 's');
// Convert memory usage to MB and display
console.log('RSS :', (mem.rss / 1024 / 1024).toFixed(2) + ' MB');
console.log('Heap Used :', (mem.heapUsed / 1024 / 1024).toFixed(2) + ' MB');
// Register a listener for the exit event
process.on('exit', function(code) {
console.log('Exit code:', code, '-- Okabe Rintaro: D-Mail sent successfully');
});
}
printReport();
process.exit(0);
node process_report.js === Future Gadget Lab Process Report === PID : 98765 Platform : linux Node.js : v20.11.0 CWD : /home/okabe/future-gadget-lab Uptime : 0.031s RSS : 28.47 MB Heap Used : 5.83 MB Exit code: 0 -- Okabe Rintaro: D-Mail sent successfully
Overview
The process object is a global interface for operating on and monitoring the Node.js process itself. The pattern of receiving command-line arguments with process.argv, accessing environment variables with process.env, and exiting with a specified exit code via process.exit() is especially common when implementing CLI tools.
process.stdin, process.stdout, and process.stderr are the streams for standard input, standard output, and standard error output respectively. console.log() internally calls process.stdout.write().
Common Mistakes
Common Mistake 1: Calling process.exit() in the middle of an async operation causes data to not be written
process.exit() immediately stops the event loop. It does not wait for pending asynchronous operations (file writes, network communication, etc.) to complete.
NG (calling exit before the write completes):
var fs = require('fs');
fs.writeFile('dmail.txt', 'D-Mail to Makise Kurisu', function(err) {
// This callback has not executed yet
});
process.exit(0); // Process exits before the write completes
OK (call exit inside the callback):
var fs = require('fs');
fs.writeFile('dmail.txt', 'D-Mail to Makise Kurisu', function(err) {
if (err) {
process.stderr.write('Write error: ' + err.message + '\n');
process.exit(1);
return;
}
console.log('D-Mail sent');
process.exit(0); // Exit after the write completes
});
Common Mistake 2: Forgetting that process.env values are always strings causes numeric comparisons to fail
All environment variables are strings. Even if they look like numbers, process.env.PORT is '3000' (a string), not 3000 (a number).
NG (comparing a string against a number):
// When run with PORT=3000
if (process.env.PORT == 3000) {
console.log('Starting on port 3000'); // == does type coercion, so this may accidentally pass
}
if (process.env.PORT === 3000) {
console.log('This line is never reached'); // === compares types too, so this is false
}
OK (explicitly convert to a number before comparing):
// Convert to number with Number()
if (Number(process.env.PORT) === 3000) {
console.log('Starting on port 3000');
}
// Or compare as a string
if (process.env.PORT === '3000') {
console.log('Starting on port 3000');
}
// Always convert when using the port number
var port = Number(process.env.PORT) || 3000;
If you find any errors or copyright issues, please contact us.