Kodokon kodokon.com

Command-line scripts: arguments, environment, and exit codes

You write scripts that receive arguments with process.argv, read environment variables, and return an exit code.

8 min · 3 questions

Open this lesson in Kodokon

You already use command-line programs: node, npm, git, and so on. Each one accepts arguments, the words typed after its name, which change its behavior. Let's write our own. Node exposes the global object process, which describes the currently running program - you came across it with process.version. Its property process.argv is an array that contains: at index 0, the path to Node; at index 1, the path to your script; and starting at index 2, the arguments actually typed by the user.

JAVASCRIPT
console.log(process.argv);

const args = process.argv.slice(2);
console.log("Your arguments:", args);
Save this code in args.js then run node args.js apple pear: slice(2) isolates the useful arguments.

A second source of information: environment variables. These are name/value pairs provided to the program by the system at launch time. They're used for configuration: a secret API key, debug mode, a database address, and so on. You read them in the process.env object. A missing variable is undefined: always plan for a default value, for instance with the ?? operator.

JAVASCRIPT
const level = process.env.LOG_LEVEL ?? "info";

console.log("Log level:", level);
Save this code in config.js: with no variable defined, the level is info.
BASH
LOG_LEVEL=debug node config.js
On macOS and Linux, you define a variable right before the command: the script then prints debug.

When a program finishes, it returns an exit code to the system: a number that sums up how things went. Universal convention: 0 means "success", any other value signals an error - this is what other tools and scripts check to know whether everything worked. process.exit(1) immediately stops the script with code 1. Also use console.error for error messages: it writes to the error output (stderr), a channel separate from normal output. Let's put it all together in a complete script.

JAVASCRIPT
const name = process.argv[2];

if (!name) {
  console.error("Usage: node greet.js <name>");
  process.exit(1);
}

console.log(`Hello, ${name}!`);
With no argument, greet.js explains its usage and exits with code 1; with a name, it greets and finishes with code 0.

Knowledge check

Make sure you remember the key points of this lesson.

  1. In process.argv, where is the first argument typed by the user?
    • At index 0
    • At index 2
    • At index 1
    • Always at the last index
  2. Which exit code signals that a program finished successfully?
    • 0
    • 1
    • 200
  3. How do you read the API_KEY environment variable in a Node script?
    • process.argv.API_KEY
    • env.get("API_KEY")
    • process.env.API_KEY