NodeJS by Example: Process Object

The process object is a global that provides information about and control over the current Node.js process. It's available without importing.

Environment Variables Access environment variables through process.env. Set environment variables (only affects current process) Common pattern: provide defaults

console.log('NODE_ENV:', process.env.NODE_ENV);
console.log('HOME:', process.env.HOME);
console.log('PATH:', process.env.PATH);

process.env.MY_VAR = 'my value';
console.log('MY_VAR:', process.env.MY_VAR);

const port = process.env.PORT || 3000;
const debug = process.env.DEBUG === 'true';

Command Line Arguments process.argv is an array containing command line arguments. [0] = path to node executable [1] = path to script [2+] = user arguments Parse arguments Simple flag parsing

console.log('Arguments:', process.argv);

const args = process.argv.slice(2);
console.log('User args:', args);

const verbose = args.includes('--verbose') || args.includes('-v');
const nameIndex = args.indexOf('--name');
const name = nameIndex > -1 ? args[nameIndex + 1] : 'default';

Current Working Directory Get and change the current working directory. Change directory process.chdir('/tmp'); console.log('New CWD:', process.cwd());

console.log('CWD:', process.cwd());

Process Information Access information about the running process.

console.log('Process ID:', process.pid);
console.log('Parent PID:', process.ppid);
console.log('Node version:', process.version);
console.log('Versions:', process.versions);
console.log('Platform:', process.platform); // 'darwin', 'linux', 'win32'
console.log('Architecture:', process.arch); // 'x64', 'arm64'
console.log('Title:', process.title);

Memory Usage Get memory usage statistics.

const memory = process.memoryUsage();
console.log('Memory usage:');
console.log('  RSS:', Math.round(memory.rss / 1024 / 1024), 'MB');
console.log('  Heap Total:', Math.round(memory.heapTotal / 1024 / 1024), 'MB');
console.log('  Heap Used:', Math.round(memory.heapUsed / 1024 / 1024), 'MB');
console.log('  External:', Math.round(memory.external / 1024 / 1024), 'MB');

CPU Usage Get CPU usage since process start or last call. ... do some work ...

const startUsage = process.cpuUsage();
const endUsage = process.cpuUsage(startUsage);
console.log('CPU time (microseconds):');
console.log('  User:', endUsage.user);
console.log('  System:', endUsage.system);

Uptime Get process uptime in seconds.

console.log('Uptime:', process.uptime(), 'seconds');

Exit Codes Exit the process with a status code. process.exit(0); // Success process.exit(1); // General error Set exit code without immediately exiting Listen for exit event (can't do async work here)


process.exitCode = 0;

process.on('exit', (code) => {
  console.log('Exiting with code:', code);
});

Uncaught Exceptions Handle uncaught exceptions (use sparingly - prefer proper error handling). Unhandled promise rejections

process.on('uncaughtException', (err, origin) => {
  console.error('Uncaught exception:', err.message);
  console.error('Origin:', origin);
  process.exit(1);
});

process.on('unhandledRejection', (reason, promise) => {
  console.error('Unhandled rejection:', reason);
});

Signals Handle operating system signals. Send signals to other processes process.kill(pid, 'SIGTERM');

process.on('SIGINT', () => {
  console.log('\nReceived SIGINT (Ctrl+C)');
  // Cleanup and exit
  process.exit(0);
});

process.on('SIGTERM', () => {
  console.log('Received SIGTERM');
  // Graceful shutdown
  process.exit(0);
});

Standard I/O Streams process provides stdin, stdout, and stderr streams. Read from stdin process.stdin.on('data', (data) => { console.log('Input:', data.toString()); });

process.stdout.write('Hello to stdout\n');
process.stderr.write('Hello to stderr\n');

Next Tick Schedule a callback to run before the next event loop iteration. Output: "This runs first" then "This runs before any I/O events"

process.nextTick(() => {
  console.log('This runs before any I/O events');
});

console.log('This runs first');

High Resolution Time Get high-resolution time for precise measurements. ... do something ...

const start = process.hrtime.bigint();
const end = process.hrtime.bigint();
console.log('Duration:', Number(end - start) / 1e6, 'ms');

Report Generate diagnostic reports. process.report.writeReport('./report.json'); console.log('Report directory:', process.report.directory);

Practical Example: CLI Application A pattern for building command-line applications. Usage Example: node script.js --name test -v file.txt Options: { name: 'test', v: true } Positional: ['file.txt']

function parseArgs(argv) {
  const args = argv.slice(2);
  const options = {};
  const positional = [];
  
  for (let i = 0; i < args.length; i++) {
    const arg = args[i];
    
    if (arg.startsWith('--')) {
      const key = arg.slice(2);
      const nextArg = args[i + 1];
      
      if (nextArg && !nextArg.startsWith('-')) {
        options[key] = nextArg;
        i++;
      } else {
        options[key] = true;
      }
    } else if (arg.startsWith('-')) {
      options[arg.slice(1)] = true;
    } else {
      positional.push(arg);
    }
  }
  
  return { options, positional };
}

const { options, positional } = parseArgs(process.argv);
console.log('Options:', options);
console.log('Positional:', positional);


Run with environment variable

$ NODE_ENV=production node process-object.js
# NODE_ENV: production

Run with command line arguments

$ node process-object.js --name test -v file.txt
# Arguments: ['/path/to/node', '/path/to/script.js', '--name', 'test', '-v', 'file.txt']
# Options: { name: 'test', v: true }
# Positional: ['file.txt']

Check process info

$ node -e "console.log(process.version)"
# v24.0.0