0
# Parsing and Execution
1
2
Parse arguments and execute commands with support for both synchronous and asynchronous operations.
3
4
## Capabilities
5
6
### Main Parsing Methods
7
8
Core methods for parsing command-line arguments.
9
10
```javascript { .api }
11
/**
12
* Parse arguments (sync or async based on middleware/handlers)
13
* @param args - Arguments to parse
14
* @param shortCircuit - Context object or callback
15
* @param _parseFn - Parse callback function
16
* @returns Parsed arguments or Promise
17
*/
18
parse(args?: string | string[], shortCircuit?: object | ParseCallback | boolean, _parseFn?: ParseCallback): Arguments | Promise<Arguments>;
19
20
/**
21
* Parse arguments asynchronously
22
* @param args - Arguments to parse
23
* @param shortCircuit - Context object or callback
24
* @param _parseFn - Parse callback function
25
* @returns Promise resolving to parsed arguments
26
*/
27
parseAsync(args?: string | string[], shortCircuit?: object | ParseCallback | boolean, _parseFn?: ParseCallback): Promise<Arguments>;
28
29
/**
30
* Parse arguments synchronously (throws if async middleware/handlers used)
31
* @param args - Arguments to parse
32
* @param shortCircuit - Context object or callback
33
* @param _parseFn - Parse callback function
34
* @returns Parsed arguments
35
*/
36
parseSync(args?: string | string[], shortCircuit?: object | ParseCallback | boolean, _parseFn?: ParseCallback): Arguments;
37
```
38
39
**Usage Examples:**
40
41
```javascript
42
import yargs from 'yargs';
43
import { hideBin } from 'yargs/helpers';
44
45
// Basic parsing
46
const argv = yargs(hideBin(process.argv))
47
.option('port', { type: 'number', default: 3000 })
48
.parse();
49
console.log(`Port: ${argv.port}`);
50
51
// Parse custom arguments
52
const customArgv = yargs()
53
.option('verbose', { type: 'boolean' })
54
.parse(['--verbose', '--port', '8080']);
55
56
// Async parsing (auto-detected based on async middleware/handlers)
57
const asyncArgv = await yargs()
58
.command('deploy', 'deploy app', {}, async (argv) => {
59
await deployApp(argv);
60
})
61
.parseAsync();
62
63
// Force async parsing
64
const forceAsyncArgv = await yargs()
65
.option('config', { type: 'string' })
66
.parseAsync(['--config', 'app.json']);
67
68
// Force sync parsing (throws if async operations present)
69
try {
70
const syncArgv = yargs()
71
.option('immediate', { type: 'boolean' })
72
.parseSync(['--immediate']);
73
} catch (error) {
74
console.error('Cannot use parseSync with async operations');
75
}
76
```
77
78
### Legacy argv Property
79
80
Access parsed arguments via the argv property (calls parse() internally).
81
82
```javascript { .api }
83
/**
84
* Parsed arguments (getter that calls parse())
85
* @deprecated Use parse() method instead
86
*/
87
readonly argv: Arguments;
88
```
89
90
**Usage Examples:**
91
92
```javascript
93
// Legacy usage (not recommended)
94
const yarg = yargs()
95
.option('port', { type: 'number' });
96
97
console.log(yarg.argv.port); // Calls parse() internally
98
99
// Recommended usage
100
const argv = yarg.parse();
101
console.log(argv.port);
102
```
103
104
### Context and Callbacks
105
106
Advanced parsing with context objects and callbacks.
107
108
```javascript { .api }
109
// Parse with context object
110
const contextArgv = yargs()
111
.command('process <file>', 'process file', {}, (argv) => {
112
console.log('Context:', argv.context);
113
console.log('File:', argv.file);
114
})
115
.parse(['process', 'data.txt'], { context: { userId: 123 } });
116
117
// Parse with callback
118
yargs()
119
.option('verbose', { type: 'boolean' })
120
.parse(['--verbose'], (err, argv, output) => {
121
if (err) {
122
console.error('Parse error:', err);
123
} else {
124
console.log('Parsed successfully:', argv);
125
console.log('Output:', output);
126
}
127
});
128
129
// Context object with async parsing
130
const result = await yargs()
131
.command('upload <file>', 'upload file', {}, (argv) => {
132
console.log('User ID:', argv.userId);
133
console.log('Uploading:', argv.file);
134
})
135
.parseAsync(['upload', 'image.jpg'], { userId: 456 });
136
```
137
138
### Middleware Integration
139
140
Parse with middleware for argument transformation.
141
142
```javascript { .api }
143
/**
144
* Add middleware for argument processing
145
* @param callback - Middleware function or array of functions
146
* @param applyBeforeValidation - Apply before validation (default: false)
147
* @param global - Apply globally across commands (default: true)
148
* @returns YargsInstance for chaining
149
*/
150
middleware(callback: MiddlewareCallback | MiddlewareCallback[], applyBeforeValidation?: boolean, global?: boolean): YargsInstance;
151
```
152
153
**Usage Examples:**
154
155
```javascript
156
// Middleware for path resolution
157
const argv = await yargs()
158
.option('input', { type: 'string' })
159
.middleware((argv) => {
160
if (argv.input) {
161
argv.input = path.resolve(argv.input);
162
}
163
return argv;
164
})
165
.parseAsync(['--input', './data.json']);
166
167
// Multiple middleware functions
168
const result = await yargs()
169
.option('config', { type: 'string' })
170
.middleware([
171
// Load config file
172
async (argv) => {
173
if (argv.config) {
174
const config = JSON.parse(await fs.readFile(argv.config, 'utf8'));
175
Object.assign(argv, config);
176
}
177
return argv;
178
},
179
// Validate loaded config
180
(argv) => {
181
if (!argv.database) {
182
throw new Error('Database configuration required');
183
}
184
return argv;
185
}
186
])
187
.parseAsync(['--config', 'app.json']);
188
189
// Pre-validation middleware
190
yargs()
191
.middleware((argv) => {
192
// Transform before validation runs
193
if (argv.env) {
194
argv.environment = argv.env;
195
delete argv.env;
196
}
197
return argv;
198
}, true) // Apply before validation
199
.parse();
200
```
201
202
### Environment Variable Integration
203
204
Parse environment variables alongside command-line arguments.
205
206
```javascript { .api }
207
/**
208
* Use environment variables with optional prefix
209
* @param prefix - Environment variable prefix or false to disable
210
* @returns YargsInstance for chaining
211
*/
212
env(prefix?: string | false): YargsInstance;
213
```
214
215
**Usage Examples:**
216
217
```javascript
218
// Use environment variables with prefix
219
const argv = yargs()
220
.option('port', { type: 'number' })
221
.option('debug', { type: 'boolean' })
222
.env('MYAPP')
223
.parse();
224
225
// Environment: MYAPP_PORT=3000 MYAPP_DEBUG=true
226
// Equivalent to: --port 3000 --debug
227
228
// Use environment variables without prefix
229
const envArgv = yargs()
230
.option('NODE_ENV', { type: 'string' })
231
.env('')
232
.parse();
233
234
// Disable environment variable parsing
235
const noEnvArgv = yargs()
236
.option('port', { type: 'number' })
237
.env(false)
238
.parse();
239
```
240
241
### Configuration File Integration
242
243
Load configuration from files during parsing.
244
245
```javascript { .api }
246
/**
247
* Load configuration from file or object
248
* @param key - Config option name, array, or config object
249
* @param msg - Config option description or parser function
250
* @param parseFn - Custom config parser function
251
* @returns YargsInstance for chaining
252
*/
253
config(key?: string | string[] | Dictionary, msg?: string | ConfigCallback, parseFn?: ConfigCallback): YargsInstance;
254
```
255
256
**Usage Examples:**
257
258
```javascript
259
// Load config from file
260
const argv = yargs()
261
.option('config', {
262
describe: 'Configuration file',
263
default: './config.json'
264
})
265
.config('config')
266
.option('port', { type: 'number' })
267
.parse();
268
269
// Custom config parser
270
const yamlArgv = yargs()
271
.option('config', { describe: 'YAML config file' })
272
.config('config', (configPath) => {
273
return yaml.load(fs.readFileSync(configPath, 'utf8'));
274
})
275
.parse();
276
277
// Direct config object
278
const directConfigArgv = yargs()
279
.config({
280
port: 3000,
281
debug: true,
282
database: {
283
host: 'localhost',
284
port: 5432
285
}
286
})
287
.parse();
288
289
// Multiple config files
290
const multiConfigArgv = yargs()
291
.config(['base.json', 'local.json'])
292
.parse();
293
```
294
295
### Completion Integration
296
297
Handle shell completion during parsing.
298
299
```javascript { .api }
300
/**
301
* Add shell completion support
302
* @param cmd - Completion command name
303
* @param desc - Completion command description or function
304
* @param fn - Completion function
305
* @returns YargsInstance for chaining
306
*/
307
completion(cmd?: string, desc?: string | false | CompletionFunction, fn?: CompletionFunction): YargsInstance;
308
309
/**
310
* Get completions for given arguments
311
* @param args - Arguments to complete
312
* @param done - Callback function
313
* @returns Promise of completions or void if callback provided
314
*/
315
getCompletion(args: string[], done?: (err: Error | null, completions: string[] | undefined) => void): Promise<string[] | void>;
316
317
/**
318
* Show completion script for shell
319
* @param $0 - Script name
320
* @param cmd - Completion command name
321
* @returns YargsInstance for chaining
322
*/
323
showCompletionScript($0?: string, cmd?: string): YargsInstance;
324
```
325
326
**Usage Examples:**
327
328
```javascript
329
// Basic completion
330
yargs()
331
.command('start', 'start service')
332
.command('stop', 'stop service')
333
.completion('completion', 'Generate completion script')
334
.parse();
335
336
// Custom completion function
337
yargs()
338
.option('env', { describe: 'Environment' })
339
.completion('completion', (current, argv) => {
340
if (current === 'env') {
341
return ['development', 'staging', 'production'];
342
}
343
return [];
344
})
345
.parse();
346
347
// Get completions programmatically
348
const completions = await yargs()
349
.command('deploy', 'deploy app')
350
.getCompletion(['deploy', '--']);
351
352
// Show completion script
353
yargs()
354
.completion()
355
.showCompletionScript();
356
```
357
358
### Alias Access
359
360
Get option aliases during parsing.
361
362
```javascript { .api }
363
/**
364
* Get option aliases
365
* @returns Object mapping option names to arrays of aliases
366
*/
367
getAliases(): Dictionary<string[]>;
368
```
369
370
**Usage Examples:**
371
372
```javascript
373
const yarg = yargs()
374
.option('verbose', { alias: 'v' })
375
.option('output', { alias: ['o', 'out'] });
376
377
const aliases = yarg.getAliases();
378
console.log(aliases);
379
// { verbose: ['v'], output: ['o', 'out'] }
380
381
// Use in command handler
382
yarg.command('info', 'show info', {}, (argv) => {
383
const aliases = yarg.getAliases();
384
console.log('Available aliases:', aliases);
385
}).parse();
386
```
387
388
## Types
389
390
```javascript { .api }
391
/**
392
* Parse callback function
393
*/
394
interface ParseCallback {
395
(err: Error | string | null, argv: Arguments, output: string): void;
396
}
397
398
/**
399
* Middleware callback function
400
*/
401
type MiddlewareCallback = (argv: Arguments) => Arguments | Promise<Arguments>;
402
403
/**
404
* Configuration callback function
405
*/
406
type ConfigCallback = (configPath: string) => object;
407
408
/**
409
* Completion function
410
*/
411
type CompletionFunction = (current: string, argv: Arguments, done: (completions: string[]) => void) => void;
412
413
/**
414
* Parsed command-line arguments
415
*/
416
interface Arguments {
417
/** Script name or node command */
418
$0: string;
419
/** Non-option arguments */
420
_: (string | number)[];
421
/** Arguments after the end-of-options flag -- */
422
'--'?: (string | number)[];
423
/** All remaining options */
424
[argName: string]: any;
425
}
426
427
/**
428
* Dictionary type for key-value mappings
429
*/
430
type Dictionary<T = any> = { [key: string]: T };
431
```