Command Line Args provides flexible parsing modes and configuration options to handle different command-line argument scenarios. The parsing behavior can be customized through the options parameter of the main commandLineArgs() function.
By default, parsing is strict - unknown options or values cause errors to be thrown.
/**
* Default strict parsing behavior
* - Throws on unknown options
* - Throws on unknown values
* - Throws when singular options set multiple times
*/
function commandLineArgs(optionDefinitions); // No options = strict modeUsage Examples:
import commandLineArgs from "command-line-args";
const options = [
{ name: 'verbose', alias: 'v', type: Boolean },
{ name: 'file', type: String }
];
// ✅ Valid usage
const result1 = commandLineArgs(options, { argv: ['--verbose', '--file', 'test.js'] });
// Result: { verbose: true, file: 'test.js' }
// ❌ Throws UNKNOWN_OPTION error
try {
commandLineArgs(options, { argv: ['--unknown'] });
} catch (err) {
console.log(err.name); // 'UNKNOWN_OPTION'
console.log(err.optionName); // '--unknown'
}
// ❌ Throws UNKNOWN_VALUE error
try {
commandLineArgs(options, { argv: ['orphan-value'] });
} catch (err) {
console.log(err.name); // 'UNKNOWN_VALUE'
console.log(err.value); // 'orphan-value'
}Enable partial: true to collect unknown arguments in an _unknown property instead of throwing errors.
/**
* Partial parsing configuration
* @param {boolean} partial - Collect unknown args instead of throwing
* @returns {object} Result includes _unknown array for unknown args
*/
interface PartialParsingOptions {
partial: boolean;
}Usage Examples:
const options = [
{ name: 'verbose', alias: 'v', type: Boolean },
{ name: 'file', type: String }
];
// Collect unknown arguments
const result = commandLineArgs(options, {
partial: true,
argv: ['--verbose', '--unknown', 'orphan', '--file', 'test.js', 'extra']
});
// Result: {
// verbose: true,
// file: 'test.js',
// _unknown: ['--unknown', 'orphan', 'extra']
// }Enable stopAtFirstUnknown: true to halt parsing at the first unknown argument, useful for command delegation patterns.
/**
* Stop-at-first-unknown parsing configuration
* @param {boolean} stopAtFirstUnknown - Stop parsing at first unknown
* @returns {object} Result with _unknown containing remaining args
*/
interface StopAtFirstUnknownOptions {
stopAtFirstUnknown: boolean; // Implies partial: true
}Usage Examples:
const options = [
{ name: 'verbose', alias: 'v', type: Boolean },
{ name: 'config', type: String }
];
// Stop at first unknown for command delegation
const result = commandLineArgs(options, {
stopAtFirstUnknown: true,
argv: ['--verbose', '--config', 'app.json', 'subcommand', '--sub-flag', 'value']
});
// Result: {
// verbose: true,
// config: 'app.json',
// _unknown: ['subcommand', '--sub-flag', 'value']
// }
// The _unknown array can be passed to another parser
const subResult = commandLineArgs(subCommandOptions, {
argv: result._unknown
});Enable caseInsensitive: true to match options regardless of case.
/**
* Case insensitive parsing configuration
* @param {boolean} caseInsensitive - Match options case-insensitively
*/
interface CaseInsensitiveOptions {
caseInsensitive: boolean;
}Usage Examples:
const options = [
{ name: 'verbose', alias: 'v', type: Boolean },
{ name: 'Output', alias: 'O', type: String }
];
const result = commandLineArgs(options, {
caseInsensitive: true,
argv: ['--VERBOSE', '-o', 'file.txt', '--output', 'file2.txt']
});
// All these match despite different cases:
// --VERBOSE matches 'verbose'
// -o matches alias 'O'
// --output matches 'Output'
// Result: { verbose: true, Output: 'file2.txt' }Enable camelCase: true to convert hyphenated option names to camelCase in the output.
/**
* Camel case output configuration
* @param {boolean} camelCase - Convert hyphenated names to camelCase
*/
interface CamelCaseOptions {
camelCase: boolean;
}Usage Examples:
const options = [
{ name: 'dry-run', type: Boolean },
{ name: 'output-file', type: String },
{ name: 'max-connections', type: Number }
];
const result = commandLineArgs(options, {
camelCase: true,
argv: ['--dry-run', '--output-file', 'result.txt', '--max-connections', '10']
});
// Result: {
// dryRun: true,
// outputFile: 'result.txt',
// maxConnections: 10
// }
// Note: _unknown is never camelCasedOverride the default process.argv by providing a custom argv array.
/**
* Custom argv input configuration
* @param {string[]} argv - Custom argv array instead of process.argv
*/
interface CustomArgvOptions {
argv: string[];
}Usage Examples:
const options = [
{ name: 'file', type: String },
{ name: 'verbose', type: Boolean }
];
// Parse custom arguments (testing, delegation, etc.)
const result = commandLineArgs(options, {
argv: ['--file', 'test.js', '--verbose']
});
// Result: { file: 'test.js', verbose: true }
// Parse from string (split by spaces)
const argString = '--file "my file.js" --verbose';
const result2 = commandLineArgs(options, {
argv: argString.match(/(?:[^\s"]+|"[^"]*")+/g).map(arg =>
arg.replace(/^"(.*)"$/, '$1') // Remove quotes
)
});Multiple parsing options can be combined for complex scenarios.
/**
* Combined parsing options
*/
interface CombinedParsingOptions {
argv?: string[];
partial?: boolean;
stopAtFirstUnknown?: boolean;
camelCase?: boolean;
caseInsensitive?: boolean;
}Usage Examples:
const options = [
{ name: 'dry-run', type: Boolean },
{ name: 'config-file', type: String }
];
// Complex parsing scenario
const result = commandLineArgs(options, {
argv: ['--DRY-RUN', '--CONFIG-FILE', 'app.json', 'unknown', '--more'],
partial: true, // Don't throw on unknown
camelCase: true, // Convert to camelCase
caseInsensitive: true // Match regardless of case
});
// Result: {
// dryRun: true,
// configFile: 'app.json',
// _unknown: ['unknown', '--more']
// }Command Line Args supports all major command-line notation standards:
--verbose
--output file.txt
--timeout=1000-v
-o file.txt
-t 1000-vt 1000 # Equivalent to: -v -t 1000
-abc # Equivalent to: -a -b -c--timeout=1000
--config=app.json--files one.js two.js three.js
--include *.js --include *.ts # With lazyMultiple# All equivalent ways to set the same values:
app --verbose --timeout=1000 --src one.js --src two.js
app --verbose --timeout 1000 --src one.js two.js
app -vt 1000 --src one.js two.js
app -vt 1000 one.js two.js # With defaultOptionDifferent parsing modes affect error handling behavior:
/**
* Error behavior by parsing mode
*/
interface ErrorHandlingByMode {
strict: {
unknownOption: 'throws UNKNOWN_OPTION';
unknownValue: 'throws UNKNOWN_VALUE';
alreadySet: 'throws ALREADY_SET';
};
partial: {
unknownOption: 'collects in _unknown';
unknownValue: 'collects in _unknown';
alreadySet: 'throws ALREADY_SET'; // Still throws
};
stopAtFirstUnknown: {
unknownOption: 'stops parsing, remaining in _unknown';
unknownValue: 'stops parsing, remaining in _unknown';
alreadySet: 'throws ALREADY_SET'; // Still throws
};
}Examples:
const options = [{ name: 'file', type: String }];
// Strict mode (default)
try {
commandLineArgs(options, { argv: ['--file', 'a.js', '--file', 'b.js'] });
} catch (err) {
console.log(err.name); // 'ALREADY_SET' - singular option set twice
}
// Partial mode - still throws ALREADY_SET
try {
commandLineArgs(options, {
partial: true,
argv: ['--file', 'a.js', '--file', 'b.js']
});
} catch (err) {
console.log(err.name); // 'ALREADY_SET' - partial doesn't prevent this
}
// Use multiple: true to collect multiple values
const multiOptions = [{ name: 'file', type: String, multiple: true }];
const result = commandLineArgs(multiOptions, {
argv: ['--file', 'a.js', '--file', 'b.js']
});
// Result: { file: ['a.js', 'b.js'] }