0
# Command Line Argument Parsing
1
2
UNIX-like command-line argument parser with automatic help generation, comprehensive configuration options, and robust error handling.
3
4
## Capabilities
5
6
### Main Parsing Function
7
8
Parses command-line arguments according to configuration, with automatic help generation and error handling.
9
10
```typescript { .api }
11
/**
12
* Parse command-line arguments according to configuration
13
* @param config - Configuration object defining available options
14
* @param command - Command array (defaults to process.argv)
15
* @param options - Execution options for error handling
16
* @returns Parsed options and arguments, or null on failure
17
*/
18
function getopt(
19
config: Config,
20
command?: string[],
21
options?: Options
22
): GetoptResponse | null;
23
```
24
25
**Usage Examples:**
26
27
```typescript
28
import { getopt } from "stdio";
29
30
// Basic boolean options
31
const options = getopt({
32
verbose: { key: 'v', description: 'Enable verbose output' },
33
quiet: { key: 'q', description: 'Suppress output' }
34
});
35
// Command: node app.js -v
36
// Result: { verbose: true }
37
// Command: node app.js --help (automatically shows help and exits)
38
39
// Options with arguments
40
const options = getopt({
41
output: {
42
key: 'o',
43
args: 1,
44
description: 'Output file path',
45
required: true
46
},
47
include: {
48
key: 'I',
49
args: 1,
50
multiple: true,
51
description: 'Include directories'
52
}
53
});
54
// Command: node app.js -o result.txt -I lib -I src file1.txt file2.txt
55
// Result: { output: 'result.txt', include: ['lib', 'src'], args: ['file1.txt', 'file2.txt'] }
56
57
// Default values and validation
58
const options = getopt({
59
port: {
60
key: 'p',
61
args: 1,
62
default: '3000',
63
description: 'Server port'
64
},
65
_meta_: {
66
minArgs: 1,
67
maxArgs: 3
68
}
69
});
70
```
71
72
### Configuration Interface
73
74
Defines available command-line options with their properties and constraints.
75
76
```typescript { .api }
77
interface Config {
78
[key: string]: {
79
/** Single-letter short option (e.g., 'v' for -v) */
80
key?: string;
81
/** Help text description for this option */
82
description?: string;
83
/** Allow multiple occurrences of this option */
84
multiple?: boolean;
85
/** Expected number of arguments (number or "*" for variable) */
86
args?: number | string;
87
/** @deprecated Use 'required' instead */
88
mandatory?: boolean;
89
/** This option is required */
90
required?: boolean;
91
/** Default value if option not provided */
92
default?: string | string[] | boolean;
93
/** Maximum number of positional arguments (only in _meta_) */
94
maxArgs?: number;
95
/** Minimum number of positional arguments (only in _meta_) */
96
minArgs?: number;
97
} | boolean | undefined;
98
}
99
```
100
101
**Special Configuration Keys:**
102
103
- `_meta_`: Configure positional argument constraints with `minArgs`, `maxArgs`, or `args`
104
105
**Configuration Examples:**
106
107
```typescript
108
// Boolean flag
109
{ verbose: { key: 'v', description: 'Verbose output' } }
110
111
// Required option with argument
112
{ config: { key: 'c', args: 1, required: true, description: 'Config file' } }
113
114
// Multiple values
115
{ include: { key: 'I', args: 1, multiple: true, description: 'Include paths' } }
116
117
// Variable arguments
118
{ files: { args: '*', description: 'Input files' } }
119
120
// Positional argument constraints
121
{ _meta_: { minArgs: 1, maxArgs: 5 } }
122
```
123
124
### Execution Options
125
126
Controls error handling and program behavior on parsing failures.
127
128
```typescript { .api }
129
interface Options {
130
/** Exit process on parsing failure (default: true) */
131
exitOnFailure?: boolean;
132
/** Throw exception on parsing failure (default: false) */
133
throwOnFailure?: boolean;
134
/** Print help message on parsing failure (default: true) */
135
printOnFailure?: boolean;
136
}
137
```
138
139
### Response Interface
140
141
Contains parsed options, arguments, and their values.
142
143
```typescript { .api }
144
interface GetoptResponse {
145
/** Parsed option values */
146
[key: string]: string | number | boolean | Array<string | number | boolean>;
147
/** Positional arguments (when present) */
148
args?: string[];
149
}
150
```
151
152
**Response Examples:**
153
154
```typescript
155
// Boolean options become true/false
156
{ verbose: true, quiet: false }
157
158
// Single arguments become strings
159
{ output: 'file.txt', port: '8080' }
160
161
// Multiple options become arrays
162
{ include: ['lib', 'src', 'test'] }
163
164
// Positional arguments
165
{ verbose: true, args: ['input.txt', 'output.txt'] }
166
```
167
168
### Configuration Validation
169
170
Built-in validation ensures configuration correctness and prevents conflicts.
171
172
**Reserved Options:**
173
- `--help` and `-h` are automatically handled for help display
174
- Cannot be declared in configuration
175
176
**Validation Rules:**
177
- Short keys must be single letters
178
- Required options must be provided
179
- Argument counts must match expectations
180
- Multiple options must use `multiple: true`
181
182
## Advanced Features
183
184
### Automatic Help Generation
185
186
Help messages are automatically generated from configuration and displayed on `-h` or `--help`:
187
188
```
189
USAGE: node program.js [OPTION1] [OPTION2]... arg1 arg2...
190
The following options are supported:
191
-v, --verbose Enable verbose output
192
-o, --output <ARG1> Output file path (required)
193
-I, --include <ARG1> Include directories (multiple)
194
```
195
196
### Error Handling
197
198
Comprehensive error handling with descriptive messages:
199
200
- Unknown options: `"Unknown option: --unknown"`
201
- Missing required: `"Missing option: --output"`
202
- Wrong argument count: `"Option --port requires 1 arguments, but 0 were provided"`
203
- Positional argument violations: `"At least 2 positional arguments are required, but 1 were provided"`
204
205
### Flexible Argument Formats
206
207
Supports multiple argument formats:
208
209
```bash
210
# Separate arguments
211
node app.js --output file.txt --port 3000
212
213
# Equals format
214
node app.js --output=file.txt --port=3000
215
216
# Short option clusters
217
node app.js -vf file.txt # equivalent to -v -f file.txt
218
219
# Mixed formats
220
node app.js -v --output=file.txt arg1 arg2
221
```