Unnamed parameters from command-line arguments passed as positional values. Arguments provide flexible parameter handling with support for arrays, validation, default values, and stream processing.
Arguments are created through a parent command and configured with chainable methods.
/**
* Create new argument (called from Cmd.arg())
* @param cmd Parent command instance
*/
constructor(cmd: Cmd): Arg;Usage Examples:
const cmd = COA.Cmd()
.arg() // Creates new argument
.name('filename')
.title('Input file to process')
.req()
.end(); // Return to parent commandConfigure argument names and descriptions for help text and internal use.
/**
* Set canonical argument identifier for internal use
* @param name Argument name used in parsed arguments object
* @returns Argument instance for chaining
*/
name(name: string): Arg;
/**
* Set argument description for help text
* @param title Human-readable argument description
* @returns Argument instance for chaining
*/
title(title: string): Arg;Usage Examples:
const cmd = COA.Cmd()
.arg()
.name('inputFile') // Internal name
.title('Source file to process') // Help text description
.req()
.end()
.arg()
.name('outputFile')
.title('Destination file (optional)')
.def('output.txt')
.end();Configure how arguments handle values and requirements.
/**
* Allow argument to accept multiple values
* @returns Argument instance for chaining
*/
arr(): Arg;
/**
* Make argument required
* @returns Argument instance for chaining
*/
req(): Arg;Usage Examples:
const cmd = COA.Cmd()
.arg()
.name('files')
.title('Files to process')
.arr() // Multiple values: file1.txt file2.txt file3.txt
.req() // At least one file required
.end()
.act(function(opts, args) {
console.log('Processing files:', args.files);
});
// Usage: myapp file1.txt file2.txt file3.txt
// Parsed args: { files: ['file1.txt', 'file2.txt', 'file3.txt'] }Handle argument value validation, transformation, and defaults.
/**
* Set validation/transformation function for argument values
* @param validation Function to validate and/or transform values
* @returns Argument instance for chaining
*/
val(validation: ValidationFunction): Arg;
/**
* Set default value for argument
* @param def Default value (passed through validation)
* @returns Argument instance for chaining
*/
def(def: any): Arg;
type ValidationFunction = (value: any) => any;Usage Examples:
const fs = require('fs');
const path = require('path');
const cmd = COA.Cmd()
.arg()
.name('port')
.title('Server port number')
.val(function(port) {
const num = parseInt(port);
if (isNaN(num) || num < 1 || num > 65535) {
throw new Error('Port must be between 1 and 65535');
}
return num;
})
.def(8080)
.end()
.arg()
.name('configFile')
.title('Configuration file path')
.val(function(filePath) {
const fullPath = path.resolve(filePath);
if (!fs.existsSync(fullPath)) {
throw new Error(`Configuration file not found: ${fullPath}`);
}
return fullPath;
})
.end()
.act(function(opts, args) {
console.log('Port:', args.port); // number
console.log('Config:', args.configFile); // resolved path
});
// Usage: myapp 3000 ./config.jsonBuilt-in support for input and output streams with STDIN/STDOUT shortcuts.
/**
* Make argument value an input stream (supports '-' for STDIN)
* @returns Argument instance for chaining
*/
input(): Arg;
/**
* Make argument value an output stream (supports '-' for STDOUT)
* @returns Argument instance for chaining
*/
output(): Arg;Usage Examples:
const cmd = COA.Cmd()
.arg()
.name('input')
.title('Input file or - for STDIN')
.input() // Converts to readable stream
.def(process.stdin)
.end()
.arg()
.name('output')
.title('Output file or - for STDOUT')
.output() // Converts to writable stream
.def(process.stdout)
.end()
.act(function(opts, args) {
// args.input is a readable stream
// args.output is a writable stream
args.input.pipe(args.output);
});
// Usage: myapp input.txt output.txt
// Usage: myapp - - (STDIN to STDOUT)
// Usage: cat input.txt | myapp - output.txtCustom completion functions for shell auto-completion of argument values.
/**
* Set custom completion function for argument values
* @param fn Function that returns completion options
* @returns Argument instance for chaining
*/
comp(fn: CompletionFunction): Arg;
type CompletionFunction = (opts: any) => any;Usage Examples:
const fs = require('fs');
const cmd = COA.Cmd()
.arg()
.name('format')
.title('Output format')
.comp(function(opts) {
return ['json', 'xml', 'yaml', 'csv'];
})
.end()
.arg()
.name('file')
.title('JavaScript file to process')
.comp(function(opts) {
// Return JavaScript file completions
return fs.readdirSync('.')
.filter(f => f.endsWith('.js'));
})
.end()
.arg()
.name('directory')
.title('Target directory')
.comp(function(opts) {
// Return directory completions
return fs.readdirSync('.')
.filter(f => fs.statSync(f).isDirectory());
})
.end();Methods for managing the fluent interface chain.
/**
* End argument configuration and return to parent command
* @returns Parent command instance
*/
end(): Cmd;
/**
* Apply function in argument context
* @param args Variable arguments to apply
* @returns Argument instance for chaining
*/
apply(...args: any[]): Arg;
/**
* Return rejected promise for error handling
* @param args Variable arguments for rejection
* @returns Argument instance for chaining
*/
reject(...args: any[]): Arg;Usage Examples:
function addFileValidation(arg) {
return arg.val(function(filePath) {
const fs = require('fs');
if (!fs.existsSync(filePath)) {
throw new Error(`File not found: ${filePath}`);
}
return filePath;
});
}
const cmd = COA.Cmd()
.arg()
.name('inputFile')
.title('Input file')
.apply(addFileValidation) // Apply common validation
.req()
.end()
.arg()
.name('templateFile')
.title('Template file')
.apply(addFileValidation)
.def('default-template.json')
.end();Arguments are parsed and made available in command actions as positional parameters.
Usage Examples:
const cmd = COA.Cmd()
.arg()
.name('command')
.title('Command to execute')
.req()
.end()
.arg()
.name('files')
.title('Files to process')
.arr() // Multiple values
.end()
.arg()
.name('output')
.title('Output destination')
.def('result.txt')
.end()
.act(function(opts, args) {
console.log('Command:', args.command); // string
console.log('Files:', args.files); // array or undefined
console.log('Output:', args.output); // string
// Process based on arguments
if (args.command === 'process' && args.files) {
args.files.forEach(file => {
console.log(`Processing ${file} -> ${args.output}`);
});
}
});
// Usage: myapp process file1.txt file2.txt output.txt
// Parsed args: { command: 'process', files: ['file1.txt', 'file2.txt'], output: 'output.txt' }
// Usage: myapp build
// Parsed args: { command: 'build', output: 'result.txt' }Arguments are parsed in the order they are defined and filled positionally.
Usage Examples:
const cmd = COA.Cmd()
.arg()
.name('action') // First positional arg
.title('Action to perform')
.req()
.end()
.arg()
.name('target') // Second positional arg
.title('Target for action')
.req()
.end()
.arg()
.name('options') // Remaining args (if arr())
.title('Additional options')
.arr()
.end()
.act(function(opts, args) {
console.log('Action:', args.action);
console.log('Target:', args.target);
console.log('Options:', args.options);
});
// Usage: myapp build project.json --verbose --optimize
// Parsed args: {
// action: 'build',
// target: 'project.json',
// options: ['--verbose', '--optimize']
// }Arguments provide built-in error handling for required values and validation failures.
Usage Examples:
const cmd = COA.Cmd()
.arg()
.name('count')
.title('Number of items')
.val(function(value) {
const num = parseInt(value);
if (isNaN(num) || num <= 0) {
throw new Error('Count must be a positive number');
}
return num;
})
.req()
.end()
.act(function(opts, args) {
console.log('Processing', args.count, 'items');
});
// Usage: myapp abc
// Error: Count must be a positive number
// Usage: myapp
// Error: Missing required argument: COUNT