Commands
Part of the Node.js Basics section of Coddy's Node.js journey. Lesson 3 of 24.
The tool will do several things, and the first word says which.
Destructuring takes the first word and gathers the rest into an array:
// node calc.js double 4
const [action, ...rest] = process.argv.slice(2);
if (action === 'double') {
console.log(Number(rest[0]) * 2);
}action is the first word and rest holds every word after it. A chain of if and else if picks what to do. A final else catches every word you did not plan for, a typo included.
Challenge
Easyadd <text>printsAdding: <text>.listprintsNo notes yet.- Any other word prints
Unknown command: <word>.
Run all three, then run node notes.js List with a capital L.
Try it yourself
// Your notes tool starts here.
const args = process.argv.slice(2);
console.log(`Adding: ${args.slice(1).join(' ')}`);
All lessons in Node.js Basics
1Running JavaScript on Node
Hello, NodeCommand-Line ArgumentsCommands