Nodejs Arguments Parsing With Yargs Package Part 2

This post is the continuation of Nodejs Arguments Parsing With Yargs Package Part 1

Builder property in yargs.command object

To set options for command in command's configuration object, add builder: {} property to it. The builder value is an object which will include all properties the command will have. In case of add command builder will have two properties body and title.

yargs.command({
  command: 'add',
  description: 'Add a new command',
  builder:{
    title:{
      describe: 'Notes title',
      demandOption: true,
      type: 'string'
    },
    body:{
      describe: 'Body of title',
      demandOption: true,
      type: 'string'
    }
  },
  handler: function(argv){
    //console.log('Adding a new note: ',argv)
    console.log('Title: '+ argv.title+ ' Body: '+ argv.body)
  }
})

In the above code title and body properties are added for add command. Both properties have options of describe which describe the option, type: 'string' ensure data type will be string.

demandOption: true make the property required for the command, by default its value is set to false.

Working with JSON and JS objects

To store our notes text data we will use json. First we will study JSON separately to store data to file system. First create a JS object car eg:

const car={
    name: 'Corolla',
    company: 'Toyata'
}

//convert to JSON
const carJSON = JSON.stringify(car)
console.log(carJSON)

// get back JS object
const parsedData = JSON.parse(carJSON)
console.log(parsedData)

To work with car object, we have to convert it to json to save it to file system.

As fs module only work with the string data , so we will convert object to string data using JSON.stringify.

{"name":"Corolla","company":"Toyata"} 
{ name: 'Corolla', company: 'Toyata' }

JSON.parse() will take JSON string and convert it to JavaScript object.

Storing JSON data in file system

const fs = require ('fs')
const car={
    name: 'Corolla',
    company: 'Toyata'
}
const carJSON = JSON.stringify(car)

fs.writeFileSync('1.json',carJSON)

The above code will create a JSON file and store JSON data in it using fs module.

Now read the json file and convert it to JS object.

const buffer = fs.readFileSync('1.json')
const dataJSON = buffer.toString()
const data = JSON.parse(dataJSON)
console.log(data.name)

The above code read the JSON from file and store it in data buffer. To use the buffer convert it to string using toString() method. Convert this data to JS object to using JSON.parse() for accessing the individual properties in the object eg: name, company.

##Adding CURD functionality to Application

Adding a Note

Adding a note function have three main parts

  1. First we have to load all notes using loadNotes()

    In part 1 tutorial we convert string to JSON for loading notes and revert back to string for saving as fs module will only save string or arrays.

  2. Writing a note with push method
  3. Saving a note

    To save a note it is better to implement a try and catch, if the notes.json file is not reachable catch block will display the error.

Checking for duplicate note

Filter the notes array returned by the loadNotes() function. If the title already exists than use a conditional statement to output Title already taken!!

complete code for adding note

const addNotes=function(title,body)
{
    const notes= loadNotes()
    const duplicateNotes = notes.filter(function(note){
        return note.title === title
    })
    if (duplicateNotes.length === 0)
    {
        notes.push({
            title: title,
            body: body
        })
        console.log("New note added!!")
        saveNotes(notes)
    }
    else{
        console.log("Title taken!!!")
    }
}
const loadNotes = function(){
    try {
        const dataBuffer = fs.readFileSync('notes.json')
        const dataJSON = dataBuffer.toString()
        return JSON.parse(dataJSON)
    } catch (e) {
        return []
    }
}
const saveNotes = function (notes){
    const dataJSON = JSON.stringify(notes)
    fs.writeFileSync('notes.json',dataJSON)
}

Removing a Note

Listing all Notes

Reading a Note