nopt is the option parser used internally by npm and many command-line tools.
Basic Usage
const nopt = require('nopt');
// 1. Define expected option types
const knownOpts = {
foo: [String, null],
size: ['big', 'medium', 'small'],
many: [String, Array],
debug: Boolean,
version: Boolean,
help: Boolean
};
// 2. Define short aliases
const shortHands = {
h: '--help',
v: '--version',
d: '--debug'
};
// 3. Parse arguments
const parsed = nopt(knownOpts, shortHands, process.argv, 2);
Output Structure
Given CLI command:
node app.js --size big -d input1.txt input2.txt
The resulting parsed object:
{
size: 'big',
debug: true,
argv: {
remain: ['input1.txt', 'input2.txt'], // Non-option positional arguments
cooked: ['--size', 'big', '--debug', 'input1.txt', 'input2.txt'],
original: ['--size', 'big', '-d', 'input1.txt', 'input2.txt']
}
}
Supported Types
StringBooleanNumberArrayDatepath(normalizes path strings)url(validates URL strings)- Enums:
['small', 'medium', 'large']