Advanced Parsing with yargs
You'll learn how to build professional, user-friendly command-line interfaces with automatic help text, validation, and sensible defaults using the yargs library.
While minimist gives you basic argument parsing, yargs takes it to the next level by providing commands, automatic help generation, input validation, and default values—all with minimal code.
Why yargs?
Think of yargs as a full-service concierge for your CLI, compared to minimist's basic receptionist. It not only parses arguments but also generates documentation, validates input, and guides users when they make mistakes.
Core Features
Commands: Structure your CLI with subcommands like myapp deploy or myapp status, each with their own options.
Automatic Help: Yargs generates --help text from your configuration, so users can discover what your tool does without reading external docs.
Validation: Enforce required arguments, check data types, and ensure values meet your criteria before your code runs.
Default Values: Specify fallbacks so users only need to provide non-standard options.
Basic Pattern
const yargs = require('yargs/yargs');
const { hideBin } = require('yargs/helpers');
const argv = yargs(hideBin(process.argv))
.option('port', {
alias: 'p',
type: 'number',
default: 3000,
description: 'Port to run server on'
})
.demandOption(['config'], 'Config file is required')
.help()
.argv;
console.log(`Starting on port ${argv.port}`);
The .option() method defines each flag with its type, default, and description. .demandOption() validates required arguments. .help() enables the automatic help system.
Key Takeaway: yargs transforms argument parsing from manual string manipulation into declarative configuration, automatically handling validation, defaults, and user documentation for professional CLI tools.