Command-line argument parsing library for Node.js with commands, options, and validation.
Parse arguments and execute commands with support for both synchronous and asynchronous operations.
Core methods for parsing command-line arguments.
/**
* Parse arguments (sync or async based on middleware/handlers)
* @param args - Arguments to parse
* @param shortCircuit - Context object or callback
* @param _parseFn - Parse callback function
* @returns Parsed arguments or Promise
*/
parse(args?: string | string[], shortCircuit?: object | ParseCallback | boolean, _parseFn?: ParseCallback): Arguments | Promise<Arguments>;
/**
* Parse arguments asynchronously
* @param args - Arguments to parse
* @param shortCircuit - Context object or callback
* @param _parseFn - Parse callback function
* @returns Promise resolving to parsed arguments
*/
parseAsync(args?: string | string[], shortCircuit?: object | ParseCallback | boolean, _parseFn?: ParseCallback): Promise<Arguments>;
/**
* Parse arguments synchronously (throws if async middleware/handlers used)
* @param args - Arguments to parse
* @param shortCircuit - Context object or callback
* @param _parseFn - Parse callback function
* @returns Parsed arguments
*/
parseSync(args?: string | string[], shortCircuit?: object | ParseCallback | boolean, _parseFn?: ParseCallback): Arguments;Usage Examples:
import yargs from 'yargs';
import { hideBin } from 'yargs/helpers';
// Basic parsing
const argv = yargs(hideBin(process.argv))
.option('port', { type: 'number', default: 3000 })
.parse();
console.log(`Port: ${argv.port}`);
// Parse custom arguments
const customArgv = yargs()
.option('verbose', { type: 'boolean' })
.parse(['--verbose', '--port', '8080']);
// Async parsing (auto-detected based on async middleware/handlers)
const asyncArgv = await yargs()
.command('deploy', 'deploy app', {}, async (argv) => {
await deployApp(argv);
})
.parseAsync();
// Force async parsing
const forceAsyncArgv = await yargs()
.option('config', { type: 'string' })
.parseAsync(['--config', 'app.json']);
// Force sync parsing (throws if async operations present)
try {
const syncArgv = yargs()
.option('immediate', { type: 'boolean' })
.parseSync(['--immediate']);
} catch (error) {
console.error('Cannot use parseSync with async operations');
}Access parsed arguments via the argv property (calls parse() internally).
/**
* Parsed arguments (getter that calls parse())
* @deprecated Use parse() method instead
*/
readonly argv: Arguments;Usage Examples:
// Legacy usage (not recommended)
const yarg = yargs()
.option('port', { type: 'number' });
console.log(yarg.argv.port); // Calls parse() internally
// Recommended usage
const argv = yarg.parse();
console.log(argv.port);Advanced parsing with context objects and callbacks.
// Parse with context object
const contextArgv = yargs()
.command('process <file>', 'process file', {}, (argv) => {
console.log('Context:', argv.context);
console.log('File:', argv.file);
})
.parse(['process', 'data.txt'], { context: { userId: 123 } });
// Parse with callback
yargs()
.option('verbose', { type: 'boolean' })
.parse(['--verbose'], (err, argv, output) => {
if (err) {
console.error('Parse error:', err);
} else {
console.log('Parsed successfully:', argv);
console.log('Output:', output);
}
});
// Context object with async parsing
const result = await yargs()
.command('upload <file>', 'upload file', {}, (argv) => {
console.log('User ID:', argv.userId);
console.log('Uploading:', argv.file);
})
.parseAsync(['upload', 'image.jpg'], { userId: 456 });Parse with middleware for argument transformation.
/**
* Add middleware for argument processing
* @param callback - Middleware function or array of functions
* @param applyBeforeValidation - Apply before validation (default: false)
* @param global - Apply globally across commands (default: true)
* @returns YargsInstance for chaining
*/
middleware(callback: MiddlewareCallback | MiddlewareCallback[], applyBeforeValidation?: boolean, global?: boolean): YargsInstance;Usage Examples:
// Middleware for path resolution
const argv = await yargs()
.option('input', { type: 'string' })
.middleware((argv) => {
if (argv.input) {
argv.input = path.resolve(argv.input);
}
return argv;
})
.parseAsync(['--input', './data.json']);
// Multiple middleware functions
const result = await yargs()
.option('config', { type: 'string' })
.middleware([
// Load config file
async (argv) => {
if (argv.config) {
const config = JSON.parse(await fs.readFile(argv.config, 'utf8'));
Object.assign(argv, config);
}
return argv;
},
// Validate loaded config
(argv) => {
if (!argv.database) {
throw new Error('Database configuration required');
}
return argv;
}
])
.parseAsync(['--config', 'app.json']);
// Pre-validation middleware
yargs()
.middleware((argv) => {
// Transform before validation runs
if (argv.env) {
argv.environment = argv.env;
delete argv.env;
}
return argv;
}, true) // Apply before validation
.parse();Parse environment variables alongside command-line arguments.
/**
* Use environment variables with optional prefix
* @param prefix - Environment variable prefix or false to disable
* @returns YargsInstance for chaining
*/
env(prefix?: string | false): YargsInstance;Usage Examples:
// Use environment variables with prefix
const argv = yargs()
.option('port', { type: 'number' })
.option('debug', { type: 'boolean' })
.env('MYAPP')
.parse();
// Environment: MYAPP_PORT=3000 MYAPP_DEBUG=true
// Equivalent to: --port 3000 --debug
// Use environment variables without prefix
const envArgv = yargs()
.option('NODE_ENV', { type: 'string' })
.env('')
.parse();
// Disable environment variable parsing
const noEnvArgv = yargs()
.option('port', { type: 'number' })
.env(false)
.parse();Load configuration from files during parsing.
/**
* Load configuration from file or object
* @param key - Config option name, array, or config object
* @param msg - Config option description or parser function
* @param parseFn - Custom config parser function
* @returns YargsInstance for chaining
*/
config(key?: string | string[] | Dictionary, msg?: string | ConfigCallback, parseFn?: ConfigCallback): YargsInstance;Usage Examples:
// Load config from file
const argv = yargs()
.option('config', {
describe: 'Configuration file',
default: './config.json'
})
.config('config')
.option('port', { type: 'number' })
.parse();
// Custom config parser
const yamlArgv = yargs()
.option('config', { describe: 'YAML config file' })
.config('config', (configPath) => {
return yaml.load(fs.readFileSync(configPath, 'utf8'));
})
.parse();
// Direct config object
const directConfigArgv = yargs()
.config({
port: 3000,
debug: true,
database: {
host: 'localhost',
port: 5432
}
})
.parse();
// Multiple config files
const multiConfigArgv = yargs()
.config(['base.json', 'local.json'])
.parse();Handle shell completion during parsing.
/**
* Add shell completion support
* @param cmd - Completion command name
* @param desc - Completion command description or function
* @param fn - Completion function
* @returns YargsInstance for chaining
*/
completion(cmd?: string, desc?: string | false | CompletionFunction, fn?: CompletionFunction): YargsInstance;
/**
* Get completions for given arguments
* @param args - Arguments to complete
* @param done - Callback function
* @returns Promise of completions or void if callback provided
*/
getCompletion(args: string[], done?: (err: Error | null, completions: string[] | undefined) => void): Promise<string[] | void>;
/**
* Show completion script for shell
* @param $0 - Script name
* @param cmd - Completion command name
* @returns YargsInstance for chaining
*/
showCompletionScript($0?: string, cmd?: string): YargsInstance;Usage Examples:
// Basic completion
yargs()
.command('start', 'start service')
.command('stop', 'stop service')
.completion('completion', 'Generate completion script')
.parse();
// Custom completion function
yargs()
.option('env', { describe: 'Environment' })
.completion('completion', (current, argv) => {
if (current === 'env') {
return ['development', 'staging', 'production'];
}
return [];
})
.parse();
// Get completions programmatically
const completions = await yargs()
.command('deploy', 'deploy app')
.getCompletion(['deploy', '--']);
// Show completion script
yargs()
.completion()
.showCompletionScript();Get option aliases during parsing.
/**
* Get option aliases
* @returns Object mapping option names to arrays of aliases
*/
getAliases(): Dictionary<string[]>;Usage Examples:
const yarg = yargs()
.option('verbose', { alias: 'v' })
.option('output', { alias: ['o', 'out'] });
const aliases = yarg.getAliases();
console.log(aliases);
// { verbose: ['v'], output: ['o', 'out'] }
// Use in command handler
yarg.command('info', 'show info', {}, (argv) => {
const aliases = yarg.getAliases();
console.log('Available aliases:', aliases);
}).parse();/**
* Parse callback function
*/
interface ParseCallback {
(err: Error | string | null, argv: Arguments, output: string): void;
}
/**
* Middleware callback function
*/
type MiddlewareCallback = (argv: Arguments) => Arguments | Promise<Arguments>;
/**
* Configuration callback function
*/
type ConfigCallback = (configPath: string) => object;
/**
* Completion function
*/
type CompletionFunction = (current: string, argv: Arguments, done: (completions: string[]) => void) => void;
/**
* Parsed command-line arguments
*/
interface Arguments {
/** Script name or node command */
$0: string;
/** Non-option arguments */
_: (string | number)[];
/** Arguments after the end-of-options flag -- */
'--'?: (string | number)[];
/** All remaining options */
[argName: string]: any;
}
/**
* Dictionary type for key-value mappings
*/
type Dictionary<T = any> = { [key: string]: T };Install with Tessl CLI
npx tessl i tessl/npm-yargs