Sample Video Frame

Created by Zed A. Shaw Updated 2024-02-17 04:54:36

08: Command Line Arguments

A command line is where you type commands in your terminal (aka PowerShell on Windows). In this exercise you learn how to get information from users by letting them put arguments after your .js file name like this:

$ node ex08.js Zed 44 Blue

The words "Zed", "44", and "Blue" after the script named ex08.js get passed to the script so you can work with them. In Node this is in the process.argv variable, and this variable is a list of the items on the command line.

I'm going to avoid telling you what a list is and save that for later (when we talk about Arrays). For now, just know that argument 1 ("Zed") is at position 2 in the process.argv and you tell JavaScript you want position 2 with [2] after process.argv. Just remember that your arguments are "off by one".

The Code

Type this in and pay attention to the type of string I'm using. See the ${} characters inside them? That means you have to use the back-tick (`) character for them or else those variables won't be placed inside the string properly.

let name = process.argv[2];
let age = process.argv[3];
let eyes = process.argv[4];

console.log(`Your name is ${name}`);
console.log(`Your age is ${age}`);
console.log(`Your eyes are ${eyes}`);

What You Should See

Command line arguments are definitely the sort of thing you want to play with so don't just run this once and leave it. Change this file and make it do new things until you feel you understand it.

$ node "ex08.js" Zed 44 Blue
Your name is Zed
Your age is 44
Your eyes are Blue
Previous Lesson Next Lesson

Register for Learn JavaScript the Hard Way

Register today for the course and get the all currently available videos and lessons, plus all future modules for no extra charge.