The global process object is an EventEmitter representing the currently running Node.js OS process. It gives your code access to environment variables (process.env), command-line arguments (process.argv), memory diagnostics, exit codes, and Unix shutdown signals like SIGTERM.
process.env, process.argv, and Memory StatsStore secrets and ports in process.env, parse CLI flags from process.argv.slice(2) (or util.parseArgs() in Node 18.3+), and remember that every value in process.env is always a string (or undefined).
const port = Number(process.env.PORT || 3000);
const isProduction = process.env.NODE_ENV === 'production';
const cliArgs = process.argv.slice(2);
const heapMb = (process.memoryUsage().heapUsed / 1024 / 1024).toFixed(1);
console.log({ port, isProduction, cliArgs, heapMb: `${heapMb} MB` });
Notice that process.env.ENABLE_CACHE = 'false' is a non-empty string, so Boolean('false') would evaluate to true! Always compare explicitly (process.env.ENABLE_CACHE === 'true').
SIGINT & SIGTERM)When Docker, Kubernetes, or Ctrl+C stops your server, the OS sends SIGTERM or SIGINT. Listening for those signals lets your app stop accepting new HTTP connections, finish active requests, close database pools, and exit cleanly with code 0.
function registerShutdown(closeResources) {
for (const signal of ['SIGINT', 'SIGTERM']) {
process.on(signal, async () => {
console.log(`Received ${signal}, shutting down gracefully...`);
await closeResources();
process.exit(0);
});
}
}
process.exit(1) immediately before logs or DB queries flush: Hard exits drop buffered writes and active HTTP responses. Set process.exitCode = 1 and let the event loop drain cleanly when possible.if (process.env.DEBUG) without comparing 'true': Because env vars are always strings, DEBUG="false" is truthy in JavaScript!uncaughtException or unhandledRejection: Log fatal errors cleanly, flush telemetry, and exit non-zero (1) so your process manager (PM2, systemd, Docker) restarts a clean process.process.cwd() and import.meta.dirname?process.cwd() returns the terminal folder from which the user launched node, while import.meta.dirname (or __dirname) is always the folder containing the current .js file.
0 and 1 mean?Exit code 0 signals success to the shell or CI runner. Any non-zero code (commonly 1) signals failure.
commander or yargs?Node.js 18.3+ includes import { parseArgs } from 'node:util', which parses --port 8080 and boolean flags cleanly out of the box.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.