COVID19 Lockdown Dev Log – Day 22, NodeJs And NPM Yarg

What I Worked On

An app for writing, reading and removing notes with NodeJs.

What I Learned

I learned how to use the Yarg npm package for working with NodeJs commandline arguments. It’s basically allowing you to parse arguments of different types. Not that you can’t do that without it, but you would have to write all of the logic for the parsing yourself and in this case I would rather spend the time building the app.

Let’s look at an example I have. I have a simple filestructure:

-notes-app/
 -app.js
 -note.js
 -nodes.json

In ‘app.js’ I create the following ‘add’ command:

// app.js

const yargs = require('yargs');
const notes = require('./note.js');

// create 'add' command. Passes options as object. The 'builder' is for building your command. The 'handler' executes the command.
yargs.command({
    command: 'add',
    builder: {
        title: {
            describe: 'Note title',
            demandOption: true,
            type: 'string'
        },
        body: {
            describe: 'Note description',
            demandOption: true,
            type: 'string'
        }   
    },
    handler: (argv) => {
        notes.addNote(argv.title, argv.body)
    }
})

This command basically allows me to write my own custom command ‘add’, followed by two hyphens in a terminal, which takes the two required inputs defined; ‘title’ and ‘body’. The ‘demandOption’ is a boolean value that determines whether the input is required or not. So by writing this command:

node app.js add --title="Note title" --body="Note body text"

I create a new note in the ‘nodes.json’ file, which looks like so:

// notes.json

[
    {
        "title": "Note title",
        "body": "Note body text"
    },
]

I won’t make this post longer than necessary so I have left out the code that creates the node in my ‘note.js’ file 😀 You can find the full code on my GitHub here

What Distracted Me During The Day

  • A friend came by and knocked on my window, which led to a little chat 😀
  • The in-laws came by to pick something up

Resources