0
# Command System
1
2
Define commands, subcommands, and positional arguments with custom handlers and builders.
3
4
## Capabilities
5
6
### Command Definition
7
8
Define commands with handlers, builders, and configuration.
9
10
```javascript { .api }
11
/**
12
* Define a command with optional subcommands and handlers
13
* @param cmd - Command string, definition object, or array
14
* @param description - Command description
15
* @param builder - Function or object to configure command options
16
* @param handler - Function to execute when command is called
17
* @param middlewares - Array of middleware functions
18
* @param deprecated - Mark command as deprecated
19
* @returns YargsInstance for chaining
20
*/
21
command(
22
cmd: string | CommandHandlerDefinition | DefinitionOrCommandName[],
23
description?: string | boolean,
24
builder?: CommandBuilderDefinition | CommandBuilder,
25
handler?: CommandHandlerCallback,
26
middlewares?: Middleware[],
27
deprecated?: boolean
28
): YargsInstance;
29
30
/**
31
* Alias for command()
32
*/
33
commands(
34
cmd: string | CommandHandlerDefinition | DefinitionOrCommandName[],
35
description?: string | boolean,
36
builder?: CommandBuilderDefinition | CommandBuilder,
37
handler?: CommandHandlerCallback,
38
middlewares?: Middleware[],
39
deprecated?: boolean
40
): YargsInstance;
41
```
42
43
**Usage Examples:**
44
45
```javascript
46
// Basic command
47
yargs()
48
.command('serve', 'start the server', {}, (argv) => {
49
console.log(`Starting server on port ${argv.port || 3000}`);
50
})
51
.parse();
52
53
// Command with positional arguments
54
yargs()
55
.command('copy <src> <dest>', 'copy a file', (yargs) => {
56
return yargs
57
.positional('src', {
58
describe: 'source file',
59
type: 'string'
60
})
61
.positional('dest', {
62
describe: 'destination file',
63
type: 'string'
64
});
65
}, (argv) => {
66
console.log(`Copying ${argv.src} to ${argv.dest}`);
67
})
68
.parse();
69
70
// Command with builder object
71
yargs()
72
.command('deploy', 'deploy the application', {
73
env: {
74
describe: 'environment to deploy to',
75
choices: ['staging', 'production'],
76
demandOption: true
77
}
78
}, (argv) => {
79
console.log(`Deploying to ${argv.env}`);
80
})
81
.parse();
82
83
// Command definition object
84
yargs()
85
.command({
86
command: 'build [target]',
87
describe: 'build the project',
88
builder: (yargs) => {
89
return yargs.positional('target', {
90
describe: 'build target',
91
choices: ['dev', 'prod'],
92
default: 'dev'
93
});
94
},
95
handler: (argv) => {
96
console.log(`Building ${argv.target} target`);
97
}
98
})
99
.parse();
100
```
101
102
### Positional Arguments
103
104
Define positional arguments within commands.
105
106
```javascript { .api }
107
/**
108
* Define positional argument within a command
109
* @param key - Positional argument name
110
* @param opts - Positional argument configuration
111
* @returns YargsInstance for chaining
112
*/
113
positional(key: string, opts: PositionalDefinition): YargsInstance;
114
```
115
116
**Usage Examples:**
117
118
```javascript
119
yargs()
120
.command('upload <file> [destination]', 'upload a file', (yargs) => {
121
return yargs
122
.positional('file', {
123
describe: 'file to upload',
124
type: 'string'
125
})
126
.positional('destination', {
127
describe: 'upload destination',
128
type: 'string',
129
default: './uploads'
130
});
131
}, (argv) => {
132
console.log(`Uploading ${argv.file} to ${argv.destination}`);
133
})
134
.parse();
135
```
136
137
### Command Directory Loading
138
139
Load commands from directory structure.
140
141
```javascript { .api }
142
/**
143
* Load commands from directory
144
* @param dir - Directory path containing command files
145
* @param opts - Directory loading options
146
* @returns YargsInstance for chaining
147
*/
148
commandDir(dir: string, opts?: RequireDirectoryOptions): YargsInstance;
149
```
150
151
**Usage Examples:**
152
153
```javascript
154
// Load all commands from ./commands directory
155
yargs()
156
.commandDir('./commands')
157
.parse();
158
159
// Load with options
160
yargs()
161
.commandDir('./commands', {
162
extensions: ['js', 'ts'],
163
recurse: true,
164
exclude: /\.test\./
165
})
166
.parse();
167
168
// Command file example (./commands/serve.js):
169
// module.exports = {
170
// command: 'serve [port]',
171
// describe: 'start the server',
172
// builder: {
173
// port: {
174
// default: 3000,
175
// type: 'number'
176
// }
177
// },
178
// handler: (argv) => {
179
// console.log(`Server starting on port ${argv.port}`);
180
// }
181
// };
182
```
183
184
### Default Commands
185
186
Define default commands that run when no command is specified.
187
188
```javascript { .api }
189
// Default command using special syntax
190
yargs()
191
.command('$0 [name]', 'default command', (yargs) => {
192
return yargs.positional('name', {
193
describe: 'name to greet',
194
default: 'World'
195
});
196
}, (argv) => {
197
console.log(`Hello, ${argv.name}!`);
198
})
199
.parse();
200
201
// Alternative syntax with *
202
yargs()
203
.command('* [name]', 'default command', (yargs) => {
204
return yargs.positional('name', {
205
describe: 'name to greet',
206
default: 'World'
207
});
208
}, (argv) => {
209
console.log(`Hello, ${argv.name}!`);
210
})
211
.parse();
212
```
213
214
### Command Aliases
215
216
Define command aliases for alternative names.
217
218
```javascript { .api }
219
// Command with aliases
220
yargs()
221
.command(['start', 'run', 's'], 'start the application', {}, (argv) => {
222
console.log('Starting application...');
223
})
224
.parse();
225
226
// Or in command definition object
227
yargs()
228
.command({
229
command: 'install [packages..]',
230
aliases: ['i', 'add'],
231
describe: 'install packages',
232
handler: (argv) => {
233
console.log(`Installing: ${argv.packages.join(', ')}`);
234
}
235
})
236
.parse();
237
```
238
239
### Subcommands
240
241
Create hierarchical command structures.
242
243
```javascript { .api }
244
// Git-like subcommand structure
245
yargs()
246
.command('git', 'git commands', (yargs) => {
247
return yargs
248
.command('clone <repo>', 'clone a repository', {}, (argv) => {
249
console.log(`Cloning ${argv.repo}`);
250
})
251
.command('push [remote]', 'push to remote', {}, (argv) => {
252
console.log(`Pushing to ${argv.remote || 'origin'}`);
253
})
254
.demandCommand(1, 'You need at least one git command');
255
})
256
.parse();
257
```
258
259
### Command Middleware
260
261
Add middleware to commands for argument processing.
262
263
```javascript { .api }
264
yargs()
265
.command('process <file>', 'process a file', {}, (argv) => {
266
// This handler receives processed argv
267
console.log(`Processing ${argv.file} as ${argv.processedType}`);
268
}, [
269
// Middleware to process file type
270
(argv) => {
271
argv.processedType = path.extname(argv.file).slice(1);
272
return argv;
273
}
274
])
275
.parse();
276
```
277
278
### Command Recommendations
279
280
Enable command recommendations for typos.
281
282
```javascript { .api }
283
/**
284
* Enable command recommendations for similar commands
285
* @param recommend - Whether to recommend similar commands
286
* @returns YargsInstance for chaining
287
*/
288
recommendCommands(recommend?: boolean): YargsInstance;
289
```
290
291
**Usage Examples:**
292
293
```javascript
294
yargs()
295
.command('start', 'start the server')
296
.command('stop', 'stop the server')
297
.recommendCommands()
298
.parse();
299
300
// Running "node app.js strt" would suggest "start"
301
```
302
303
## Types
304
305
```javascript { .api }
306
/**
307
* Command handler callback function
308
*/
309
type CommandHandlerCallback = (argv: Arguments) => void | Promise<void>;
310
311
/**
312
* Command builder function
313
*/
314
type CommandBuilder = (yargs: YargsInstance) => YargsInstance | Promise<YargsInstance>;
315
316
/**
317
* Command builder definition object
318
*/
319
interface CommandBuilderDefinition {
320
[key: string]: OptionDefinition;
321
}
322
323
/**
324
* Complete command handler definition
325
*/
326
interface CommandHandlerDefinition {
327
command?: string | string[];
328
aliases?: string | string[];
329
describe?: string | boolean;
330
desc?: string | boolean;
331
description?: string | boolean;
332
builder?: CommandBuilder | CommandBuilderDefinition;
333
handler: CommandHandlerCallback;
334
middlewares?: Middleware[];
335
deprecated?: boolean | string;
336
}
337
338
/**
339
* Positional argument definition
340
*/
341
interface PositionalDefinition {
342
alias?: string | string[];
343
choices?: string | string[];
344
coerce?: (arg: any) => any;
345
conflicts?: string | string[];
346
default?: any;
347
defaultDescription?: string;
348
desc?: string;
349
describe?: string;
350
description?: string;
351
implies?: string | number | (string | number)[];
352
normalize?: boolean;
353
type?: 'boolean' | 'number' | 'string';
354
}
355
356
/**
357
* Directory loading options
358
*/
359
interface RequireDirectoryOptions {
360
extensions?: ReadonlyArray<string>;
361
visit?: (commandObject: any, pathToFile: string, filename?: string) => any;
362
recurse?: boolean;
363
include?: RegExp | ((fileName: string) => boolean);
364
exclude?: RegExp | ((fileName: string) => boolean);
365
}
366
367
/**
368
* Middleware function
369
*/
370
type Middleware = (argv: Arguments) => Arguments | Promise<Arguments>;
371
```