3.16 Requiring Arguments and Advanced Yargs

We are learning how to configure Yargs for command line interface. We are learning how to set up the command and their descriptions for their arguments.

Go to Yargs for documentations.

const argv = yargs
.command(
'add',
'Add a new note'
)
.help() // sets up yargs to return some important info (enable --help)
.argv;

.help()

Notice that .help() enables the --help flag.
When you run node app.js --help, it displays a summary of helpful information.

$ node app.js --help
Commands:
add Add a new note
Options:
--help Show help [boolean]

When you run node node.js add --help, it displays add-specific help information.

$ node app.js add --help
Note created
--
Title: undefined
Body: undefined

We notice that the info is not correct. Now we are going to set these correct.

.command(
'add',
'Add a new note',
{
title : {
describe: 'Title of note',
demand: true // force this argument
}
}
)

We added another object that specifies the help messages for each argument.

Let’s check demand!

$ node app.js add
app.js add
Options:
--help Show help [boolean]
--title Title of note [required]
Missing required argument: title

Use Alias to provide a short cut.

describe: 'Title of note',
demand: true, // force this argument
alias: 't'

This enables node app.js add -t "flag title" --body="flag body"

Let’s do the exact the same thing for body.

body : {
describe: 'Body of note',
demand: true,
alias: 'b'
}

Use it.

$ node app.js add -t=t -b=b
Note created
--
Title: t
Body: b

There are three more commands to do.

var titleOptions = {
describe: 'Title of note',
demand: true, // force this argument
alias: 't'
}
var bodyOptions = {
describe: 'Body of note',
demand: true,
alias: 'b'
}
const argv = yargs
.command(
'add',
'Add a new note',
{
title : titleOptions,
body : bodyOptions
}
)
.command('list', 'List all notes')
.command('read', 'Read a note',
{
title : titleOptions
})
.command('remove', 'Remove a note',
{
title : titleOptions
})
.help() // sets up yargs to return some important info (enable --help)
.argv;