Command-Line Arguments
Part of the Node.js Basics section of Coddy's Node.js journey. Lesson 2 of 24.
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']. Quotes keep words together: node greet.js "Ada Lovelace" gives one string.
Challenge
Easynode notes.js add Buy milkprintsAdding: Buy milk.- Every word after
addbelongs to the note.
Run it with a note of your own, then run node notes.js add with no words.
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, NodeCommand-Line ArgumentsCommands