This page is not available in every language. Missing translations are disabled in the language selector.

Quick reference

Node.js process Module Cheatsheet

A quick reference guide for the Node.js process global object: command-line arguments, environment variables, exit codes, stdio streams, and working directories.

· Published

The global process object provides control over the current Node.js process runtime, environment variables, standard streams, and lifecycle events.

Standard I/O Streams

// Direct writing to standard output and error without extra newline
process.stdout.write('Processing task...\n');
process.stderr.write('Warning: unexpected payload\n');

// Reading from standard input
function readStdin(callback) {
  let data = '';
  process.stdin.setEncoding('utf8');

  process.stdin.on('readable', () => {
    const chunk = process.stdin.read();
    if (chunk !== null) data += chunk;
  });

  process.stdin.on('end', () => {
    callback(null, data);
  });
}

Runtime Metadata & Arguments

// Command line arguments array
// Running: node script.js --mode=prod input.txt
process.argv;
// => ['/path/to/node', '/path/to/script.js', '--mode=prod', 'input.txt']

// Environment variables dictionary
const port = process.env.PORT || 3000;
const isDev = process.env.NODE_ENV !== 'production';

// Process ID and platform architecture
process.pid;      // Process ID integer
process.platform; // 'darwin', 'linux', 'win32'
process.arch;     // 'x64', 'arm64'

Directory Navigation

// Current working directory
console.log(process.cwd()); // e.g. "/Users/project"

// Change working directory
process.chdir('/tmp');

Process Termination & Exit Codes

// Successful clean termination
process.exit(0);

// Non-zero error exit
process.exit(1);

// Intercept exit event
process.on('exit', (code) => {
  console.log(`Process exited with code: ${code}`);
});

// Intercept unhandled exceptions
process.on('uncaughtException', (err) => {
  console.error('Fatal crash:', err);
  process.exit(1);
});

References

Related topics