What is the `process` object? How do you read environment variables and CLI arguments?

3 minbeginnernodejsprocessenvargvsignals

Quick Answer

`process` is a global giving information about and control over the current Node process: `process.env` for environment variables, `process.argv` for command-line arguments, `process.cwd()`, `process.exit()`, and events like `SIGINT` and `beforeExit` for lifecycle/shutdown handling.

Detailed Answer

Answer: process is a global object that represents the running Node process and lets you interact with the OS-level environment.

Environment variables — process.env:

// Read config from the environment (12-factor style)
const port = process.env.PORT || 3000;
const dbUrl = process.env.DATABASE_URL;

Values are always strings (or undefined). Use them for secrets and per-environment config instead of hardcoding.

Command-line arguments — process.argv:

// node app.js --name Alice
console.log(process.argv);
// [ '/path/to/node', '/path/to/app.js', '--name', 'Alice' ]
const args = process.argv.slice(2); // just your args

Other commonly used members:

  • process.cwd() — current working directory.
  • process.platform / process.arch — OS and CPU architecture.
  • process.pid — process id.
  • process.exit(code) — exit immediately with a status code (avoid unless necessary; prefer letting the event loop drain).
  • process.nextTick(cb) — run a callback before the next event-loop phase.
  • process.memoryUsage() — heap/RSS stats.

Lifecycle events (useful for graceful shutdown):

process.on('SIGINT', () => { /* Ctrl+C: close servers, DB, then exit */ });
process.on('SIGTERM', () => { /* container stop */ });
process.on('uncaughtException', (err) => { /* log, then exit */ });
process.on('unhandledRejection', (reason) => { /* log */ });