Yargs
Command line parser for Node.js that builds help, subcommands, validation, and typed options with minimal boilerplate.
Official Documentation ↗v17. Check the official docs for the latest API surface.Installation
npm install yargspnpm add yargsMethods
No methods match this filter.
Command line parser for Node.js that builds help, subcommands, validation, and typed options with minimal boilerplate.
Overview
Yargs turns a pile of argv handling into declarative configuration. Options declare aliases, defaults, types, and descriptions; Yargs assembles usage text, validates required inputs, and maps dotted and dashed flags into a predictable argv object.
At the command level, builders compose subcommand-specific options while handlers receive fully parsed argv. demandCommand and strict modes keep typos from silently becoming undefined values, and middleware or fail hooks integrate the parser with your logging and exit-code conventions.
Core Methods
The most frequently used entry points, with signatures and runnable examples:
yargs().parse— Parses argv with declared options; the resulting object carries camelCase keys for dashed flags.command— Registers a subcommand with its own builder for options and a handler receiving parsed argv.fail— Replaces the default validation failure output to control exit codes and error formatting.
Usage Notes
- Set process.exitCode instead of calling process.exit inside handlers so async cleanup can finish.
- Use choices to constrain positional values early; rejecting “prodcution” at parse time beats a mystery deploy failure.
- Generate completion with .completion() during development to sanity-check your option surface.
Common Pitfalls
- In ESM, argv is not available at import time; pass process.argv.slice(2) explicitly instead of relying on ambient state.
- Dashed flags become camelCase keys: –output-dir arrives as argv.outputDir, and reading argv[“output-dir”] returns undefined.
- Handlers run synchronously by default; await async work via promise-returning handlers or top-level await orchestration outside yargs.
FAQ
- How do I import yargs in ESM?
- Use import { yargs } from "yargs" and call yargs() explicitly, or import yargs from "yargs/helpers" utilities for parsing helpers. The old default export pattern belongs to CommonJS.
- How do required positional arguments work?
- Declare them with angle brackets in the command string, for example "rollout <env>", and describe them with positional. Parsing fails with a usage message when the argument is missing, unless fail overrides that behavior.
- How can unknown flags become errors?
- Chain strict() so undeclared options abort parsing with a clear message. strictCommands() and strictOptions() apply the same discipline to subcommands and flags separately.
Report a problem with this API docOpens a pre-filled issue on GitHub.