Node.js Process
Node.js Process: Environment Variables, CLI Args, and Graceful Shutdown
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.
Reading process.env, process.argv, and Memory Stats
Store 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').
Handling Graceful Shutdown (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);
});
}
}
Common Mistakes to Avoid
- Calling
process.exit(1)immediately before logs or DB queries flush: Hard exits drop buffered writes and active HTTP responses. Setprocess.exitCode = 1and let the event loop drain cleanly when possible. - Checking
if (process.env.DEBUG)without comparing'true': Because env vars are always strings,DEBUG="false"is truthy in JavaScript! - Ignoring
uncaughtExceptionorunhandledRejection: Log fatal errors cleanly, flush telemetry, and exit non-zero (1) so your process manager (PM2, systemd, Docker) restarts a clean process.
Frequently Asked Questions
What is the difference between 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.
What do Node.js exit codes 0 and 1 mean?
Exit code 0 signals success to the shell or CI runner. Any non-zero code (commonly 1) signals failure.
How can I parse CLI flags without installing 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.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.