المعرفة:: NodeJS الحالة::مؤرشفة المراجع:: The Complete Node.js Developer Course 3rd Edition, coggro’s Notes
Introduction
- Node.js provides a bare-bones way to access command line arguments. While it’s a good start, it doesn’t provide any way to parse more complex command line arguments.
- Yargs helps you build interactive command line tools, by parsing arguments and generating an elegant user interface.
- https://www.npmjs.com/package/yargs
Installing and Setting Up Yargs
- yargs can be used to make it easier to work with command line arguments. The example below shows how this can be done. First,
yargs.version
is used to set up a version for the command line tool. Next,yargs.command
is used to add support for a new command.
- This command can be triggered by providing its name as a command line argument.
- Yargs provides a many useful commands by default, such as tool’s version and auto-generated documentation that explains how the tool can be used.
- Yargs exposes a much more reasonable object of arguments:
node app.js add --title="things to buy"
yields{ _: [ 'add' ], title: 'things to buy', '$0': 'app.js' }
. - We can set up commands using
.command({command object})
function.
Adding Command Options
- Options are additional pieces of information passed along with the command. You can set up options for a command using the
builder
property as shown below. - The
add
command can be used with two options. The first istitle
which is used for the title of the note being added. The second isbody
which is used for the body of the note being added. Both options are required becausedemandOption
is set to true. Both are also set up to accept string input because type is set to ‘string
’.
- Accessing
argv
from the actual args object forces it to actually parse.console.log(args.argv)
. However, we can force a parse without logging by usingargs.parse()
.