Command-Line Arguments
Part of the Node.js Basics section of Coddy's Node.js journey. Lesson 3 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
const args = process.argv.slice(2);
console.log(`Hello, ${args[0]}!`);node greet.js Ada prints Hello, Ada!. Each word arrives as its own string, so node greet.js Ada Lovelace gives args the value ['Ada', 'Lovelace']. To put words back into one string, use join(' '): ['Ada', 'Lovelace'].join(' ') is 'Ada Lovelace'. Quotes keep words together: node greet.js "Ada Lovelace" gives one string.
Challenge
EasyYour notes tool needs to know what you typed after node notes.js. Here it reads a note from the command and repeats it back.
- In
notes.js, read the words typed afternode notes.jswithprocess.argv. The first word is the command,add. For now it is alwaysadd. Every word after it is the note. - The note's words arrive as separate strings. Put them back together into one string, with one space between words.
- Replace the starter's
console.log('Adding:')line. Print one line:Adding:followed by the note.
For node notes.js add Buy milk the program prints:
Adding: Buy milkFor node notes.js add Call Ada tonight it prints:
Adding: Call Ada tonightPut one space after Adding:.
Try it: in the terminal, type add Buy milk in the box after $ node notes.js and press Enter. You see Adding: Buy milk. Then type a note of your own, such as add Call Ada tonight. Last, type only add: you see Adding: with nothing after it, because there is no note. That is fine for now.
Try it yourself
// Your notes tool starts here.
// node notes.js add Buy milk should print: Adding: Buy milk
console.log('Adding:');
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Node.js Basics
1Running JavaScript on Node
Hello, NodeReading the CommandCommand-Line ArgumentsCommandsPractice on your own: Express playground