Command-Line Arguments

Junior Year, page 6 of 11. A one-minute read.

When you run a Node program, you can pass extra words after the file name. Node puts them in an array called process.argv (short for "argument values"):

greet.js
console.log(process.argv);
Terminal
node greet.js Omar 25

Output

[
  '/usr/local/bin/node',
  '/home/you/node-practice/greet.js',
  'Omar',
  '25'
]

The first two items are always the path to Node itself and the path to your file. The words you typed start at index 2. So usually you'll slice them off:

greet.js
const [name = "stranger", age] = process.argv.slice(2);

if (age) {
  console.log(`Hello, ${name}! Next year you'll be ${Number(age) + 1}.`);
} else {
  console.log(`Hello, ${name}!`);
}
Terminal
node greet.js Omar 25

Output

Hello, Omar! Next year you'll be 26.

(Destructuring with a default value, from Grade 13! And notice we converted age with Number(), because command-line arguments are always strings, just like prompt and input values.)

This is how command-line tools work. Every time you've typed something like node --version, the --version part was a command-line argument.

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning