Menu
CoddyTech

Reading the Command

Part of the Node.js Basics section of Coddy's Node.js journey. Lesson 2 of 33.

A notes tool has to know what you typed after its name.

process.argv is an array of the words in the command: the path to Node, the path to your file, then your words. slice(2) keeps only yours.

// node greet.js Ada Lovelace
const args = process.argv.slice(2);
console.log('First name: ' + args[0]);

node greet.js Ada Lovelace prints First name: Ada. Here args is ['Ada', 'Lovelace']: args[0] is the first word you typed and args[1] the second. Each word arrives as a string.

challenge icon

Challenge

Easy

Your notes tool will understand commands such as add and list. First it needs to read which command you typed after node notes.js.

  1. In notes.js, read the words typed after node notes.js with process.argv.slice(2).
  2. Replace the starter's console.log('Command:') line. Print one line: Command: followed by the first word.

For node notes.js add Buy milk the program prints:

Command: add

For node notes.js list it prints:

Command: list

Try it: in the terminal, type add Buy milk in the box after $ node notes.js and press Enter. Then try list.

Try it yourself

// Your notes tool starts here.
// node notes.js add Buy milk should print: Command: add
console.log('Command:');

All lessons in Node.js Basics

Practice on your own: Express playground