process, argv & Environment Variables
8 min read
The process Object
The global process object provides information about and control over the current Node.js process. It is available everywhere without importing — no require needed.
Environment Variables
process.env is a plain object holding all environment variables. It is the standard way to pass secrets, configuration, and environment-specific settings to your app without hardcoding them.
js
// Access environment variables
const port = process.env.PORT || "3000";
const dbUrl = process.env.DATABASE_URL;
const env = process.env.NODE_ENV || "development";
console.log(`Starting in ${env} on port ${port}`);
// Exit with a code (0 = success, non-zero = error)
if (!dbUrl) {
console.error("DATABASE_URL is required");
process.exit(1);
}Command-Line Arguments with process.argv
process.argv is an array of strings: index 0 is the path to node, index 1 is the script path, and index 2 onwards are any arguments you passed.
js
// greet.js
const args = process.argv.slice(2); // Remove 'node' and script path
const name = args[0] || "World";
console.log(`Hello, ${name}!`);bash
node greet.js Alice
# Hello, Alice!
node greet.js
# Hello, World!Never commit .env files containing real secrets to version control. Use .env.example to document required variables and load them with the dotenv package.
Ready to test yourself?
Practice Node.js— quiz & coding exercises