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
EasyYour notes tool will understand commands such as add and list. First it needs to read which command you typed after node notes.js.
- In
notes.js, read the words typed afternode notes.jswithprocess.argv.slice(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: addFor node notes.js list it prints:
Command: listTry 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
1Running JavaScript on Node
Hello, NodeReading the CommandCommand-Line ArgumentsCommandsPractice on your own: Express playground