Bootcamp
Search…
📅
Course Schedule
0: Language and Tooling Teaching Guide
1: Frontend Basics Teaching Guide
2: Backend Basics Teaching Guide
3: Backend Applications Teaching Guide
4: Backend Structure Teaching Guide
5: Full-Stack Applications Teaching Guide
6: Frontend Infrastructure Teaching Guide
7: React Teaching Guide
8: Advanced React Teaching Guide
9: Advanced Topics Teaching Guide
🧮
Algorithms Teaching Guide
💼
Interview Prep Teaching Guide
☺
User Experience Teaching Guide
2.2: Command Line Programs

Introduction

We will create basic command line programs using Node.js' built-in process global variable.

process.argv is Array of Program Parameters

process.argv contains all the information about what was typed into the terminal when the Node.js program was executed. Create an index.js file that contains the following.

index.js

1
console.log('this is process argv!');
2
console.log(process.argv);
Copied!

Sample Commands

Run index.js with various inputs.
1
node index.js
Copied!
1
node index.js tomatoes
Copied!
1
node index.js apples bananas
Copied!
1
node index.js chicken pork beef
Copied!
  1. 1.
    Notice the data type of process.argv and how its contents change depending on the command-line parameters.
  2. 2.
    Notice process.argv[0] is the absolute path to the Node.js application.
  3. 3.
    Notice process.argv[1] is the absolute path to the JavaScript file that Node.js is running.

process.argv Values are Strings

The data type of process.argv values is always string.

index.js

1
console.log('Process argv values are strings!');
2
console.log(process.argv[2] + process.argv[3] + process.argv[4]);
Copied!

Sample Command

1
node index.js 1 1 1 # this will output 111, not 3
Copied!

Metric Conversion Program

Use process.argv to capture input from the user. Since the first two elements of the process.argv array will be the Node.js path and the file path, we start looking for user arguments at element 2.

Convert KM to Miles

index.js

1
const distanceInKm = process.argv[2];
2
const distanceInMiles = Number(distanceInKm) * 0.62;
3
console.log(distanceInMiles);
Copied!

Sample Command

1
node index.js 76
Copied!

Convert Litres to Gallons

Sample Command

1
node index.js 1 // this should output 0.264172
Copied!
Last modified 2mo ago