Menu
CoddyTech

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 icon

Challenge

Easy

Your 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.

  1. In notes.js, replace both starter lines. Split the words after node notes.js into the command, which is the first word, and the rest, which is every other word.
  2. Pick what to do with one if, else if, else chain on the command. Each command prints exactly one line:
    • add prints Adding: followed by the rest of the words, joined with spaces. node notes.js add Buy milk prints Adding: Buy milk.
    • list prints No 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 3 prints Unknown command: remove, without the 3.
  3. Nothing else may print. If last lesson's line that prints Adding: stays outside the chain, it runs for every command, list prints 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 milk shows Adding: Buy milk.
  • list shows No notes yet.
  • remove 3 shows Unknown command: remove.
  • List, with a capital L, shows Unknown command: List. JavaScript compares text letter by letter, capitals included, so List is not list.

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