Commands
Part of the Node.js Basics section of Coddy's Node.js journey. Lesson 4 of 33.
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. rest.join(' ') puts those words back into one string. 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
EasyYour tool will do several jobs, and the first word after node notes.js says which one. Now it learns two commands, add and list, and a reply for any word it does not know.
- In
notes.js, replace both starter lines. Split the words afternode notes.jsinto the command, which is the first word, and the rest, which is every other word. - Pick what to do with one
if,else if,elsechain on the command. Each command prints exactly one line:addprintsAdding:followed by the rest of the words, joined with spaces.node notes.js add Buy milkprintsAdding: Buy milk.listprintsNo notes yet. Notes are not saved anywhere yet; that comes in chapter 3.- Any other first word prints
Unknown command:followed by that first word only.node notes.js remove 3printsUnknown command: remove, without the3.
- Nothing else may print. If last lesson's line that prints
Adding:stays outside the chain, it runs for every command,listprints two lines, and the checks fail.
All three cases end normally, with exit code 0. The next lesson turns unknown commands into errors.
Try it: type each of these in the box after $ node notes.js and press Enter.
add Buy milkshowsAdding: Buy milk.listshowsNo notes yet.remove 3showsUnknown command: remove.List, with a capital L, showsUnknown command: List. JavaScript compares text letter by letter, capitals included, soListis notlist.
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
Practice on your own: Express playground