process — Process
The Node.js process object — argv, env, exit, stdin/stdout, signals, and working directory.
What it is, in plain English: The process object in Node.js is a global that provides information about and control over the current Node.js process. process.argv holds command-line arguments. process.env holds environment variables. process.exit() terminates the process. process.stdin and process.stdout are streams for reading and writing to the terminal. process.on('SIGINT') lets you handle Ctrl+C gracefully.
Reading args, environment, and controlling the process
Command-line arguments
// process.argv = ["node", "/path/to/script.js", ...user_args]
// node hello.js Alice 42
const [, , name, age] = process.argv;
console.log(`Hello ${name}, you are ${age} years old`);
// Parse --flag value style args:
function parseArgs() {
const args = {};
const argv = process.argv.slice(2); // skip "node" and script path
for (let i = 0; i < argv.length; i++) {
if (argv[i].startsWith("--")) {
const key = argv[i].slice(2);
const next = argv[i + 1];
args[key] = next && !next.startsWith("--") ? argv[++i] : true;
}
}
return args;
}
// node server.js --port 8080 --debug
const { port = "3000", debug = false } = parseArgs();
console.log(`Starting on port ${port}, debug: ${debug}`);Environment variables
// process.env contains all environment variables:
const dbUrl = process.env.DATABASE_URL;
const apiKey = process.env.API_KEY;
const nodeEnv = process.env.NODE_ENV ?? "development";
const isProd = nodeEnv === "production";
if (!dbUrl) {
console.error("Missing DATABASE_URL environment variable");
process.exit(1); // non-zero exit = error
}
// Load .env file with dotenv package (npm install dotenv):
// import "dotenv/config"; // at the top of your entry file
// Now process.env.MY_VAR works from .env fileExit codes and signals
// Graceful shutdown:
process.on("SIGTERM", async () => {
console.log("SIGTERM received — shutting down gracefully");
await server.close();
await db.disconnect();
process.exit(0); // 0 = success
});
// Ctrl+C:
process.on("SIGINT", () => {
console.log("
Interrupted — bye!");
process.exit(0);
});
// Catch unhandled errors (last resort — fix the root cause instead):
process.on("uncaughtException", (err) => {
console.error("Uncaught:", err);
process.exit(1); // 1 = error
});
process.on("unhandledRejection", (reason) => {
console.error("Unhandled rejection:", reason);
process.exit(1);
});
Try It Yourself
Official Sources
The Codex links only to official documentation and the ECMAScript specification. No third-party tutorials.