Skip to content
Laviyx Learn

Try

Node.js and Express course menu

Node.js process: Command-Line Arguments and Environment Variables

Use the process object in Node.js: reading command-line arguments with process.argv and util.parseArgs, environment variables with process.env, loading .env files with --env-file, exit codes, and reading input from stdin.

Beginner8 min readUpdated
On this page

The global process object describes the running Node.js program: its arguments, environment variables, working directory, memory use, and how it exits.

Command-line arguments#

process.argv is an array: the path to node, the path to your script, then the arguments you typed:

greet.js (JavaScript)
const args = process.argv.slice(2);          // skip the node and script paths
console.log("Arguments:", args);

const name = args[0] ?? "friend";
const times = Number(args[1] ?? 1);
for (let i = 0; i < times; i++) console.log(`Hello, ${name}!`);
Terminal
node greet.js Priya 2
node greet.js
Output
Arguments: [ 'Priya', '2' ]
Hello, Priya!
Hello, Priya!
Arguments: []
Hello, friend!

Arguments are always strings; convert them as needed.

Named options with parseArgs#

For flags such as --currency INR --round, use the built-in parseArgs from node:util:

convert.js (JavaScript)
import { parseArgs } from "node:util";

const { values, positionals } = parseArgs({
  options: {
    rate: { type: "string", short: "r", default: "83.2" },
    round: { type: "boolean", default: false },
  },
  allowPositionals: true,
});

const dollars = Number(positionals[0]);
const rupees = dollars * Number(values.rate);
console.log(`$${dollars} = ₹${values.round ? Math.round(rupees) : rupees.toFixed(2)}`);
Terminal
node convert.js 25
node convert.js 25 --rate 84 --round
node convert.js 10 -r 82.5
Output
$25 = ₹2080.00
$25 = ₹2100
$10 = ₹825.00

(The exchange rates here are made-up example values passed as options, not live rates.) Unknown options throw an error, which helps catch typos. Larger command-line tools often use packages such as commander or yargs.

Environment variables#

Environment variables are settings given to a program from outside: which port to listen on, database addresses, API keys, whether it runs in production. They keep configuration and secrets out of your code.

config.js (JavaScript)
const port = Number(process.env.PORT ?? 3000);
const mode = process.env.NODE_ENV ?? "development";
console.log(`Starting in ${mode} mode on port ${port}`);
console.log("API key set?", process.env.PAYMENT_API_KEY ? "yes" : "no");
Terminal
node config.js
PORT=8080 NODE_ENV=production node config.js
Output
Starting in development mode on port 3000
API key set? no
Starting in production mode on port 8080
API key set? no

The second line sets variables for one command in macOS/Linux shells (and Git Bash on Windows). In PowerShell, set them first with $env:PORT = "8080". Environment variables are always strings or undefined.

.env files#

During development, keep variables in a .env file and load it with Node's built-in --env-file option:

.env (Text)
PORT=4000
NODE_ENV=development
PAYMENT_API_KEY=test_key_123
Terminal
node --env-file=.env config.js
Output
Starting in development mode on port 4000
API key set? yes

process.loadEnvFile() does the same from inside the code. The dotenv package is the older, widely used alternative (import "dotenv/config";).

Never commit .env to Git: add it to .gitignore, and commit a .env.example with placeholder values instead, so others know which variables to set. On servers, set real environment variables in your hosting platform's settings.

Exit codes#

A program's exit code tells the shell (and CI systems, scripts, process managers) whether it succeeded: 0 means success, anything else means failure.

check-stock.js (JavaScript)
const stock = { notebook: 120, pen: 0 };
const item = process.argv[2];

if (!(item in stock)) {
  console.error(`Unknown item: ${item}`);
  process.exitCode = 2;
} else if (stock[item] === 0) {
  console.error(`${item} is out of stock`);
  process.exitCode = 1;
} else {
  console.log(`${item}: ${stock[item]} in stock`);
}
Terminal
node check-stock.js notebook; echo "exit code $?"
node check-stock.js pen; echo "exit code $?"
node check-stock.js laptop; echo "exit code $?"
Output
notebook: 120 in stock
exit code 0
pen is out of stock
exit code 1
Unknown item: laptop
exit code 2

console.error writes to stderr (the error stream), so errors can be separated from normal output. Setting process.exitCode lets the program finish normally with that code; process.exit(code) stops immediately, cutting off any pending work, so prefer exitCode.

Other process information#

JavaScript
console.log(typeof process.cwd());                  // current working directory
console.log(process.platform === "win32" || process.platform === "linux" || process.platform === "darwin");
console.log(process.memoryUsage().heapUsed > 0);
console.log(Number.isInteger(process.pid));
Output
string
true
true
true

Common mistakes#

Practice#

Practice exercise

Write discount.js that takes a price as its first argument and reads the discount percentage from the DISCOUNT environment variable (default 0). Print the final price with 2 decimals, and exit with code 1 and an error message if the price is not a positive number.

Show hint

const price = Number(process.argv[2]), check Number.isFinite(price) && price > 0, and read Number(process.env.DISCOUNT ?? 0).

Show solution
discount.js (JavaScript)
const price = Number(process.argv[2]);
const discount = Number(process.env.DISCOUNT ?? 0);

if (!Number.isFinite(price) || price <= 0) {
  console.error("Usage: node discount.js <price>");
  process.exitCode = 1;
} else {
  console.log(`Final price: ${(price * (1 - discount / 100)).toFixed(2)}`);
}
Terminal
node discount.js 1500
DISCOUNT=20 node discount.js 1500
node discount.js abc; echo "exit code $?"
Output
Final price: 1500.00
Final price: 1200.00
Usage: node discount.js <price>
exit code 1

Key takeaway#

Next: Events and EventEmitter.

Finished this lesson?