nopt は npm や多くの CLI ツールの内部で使用されているオプションパーサです。
基本的な使い方
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);
出力構造
次のような CLI コマンドを与えた場合:
node app.js --size big -d input1.txt input2.txt
得られる解析オブジェクトは次の通りです:
{
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']
}
}
サポートされる型
StringBooleanNumberArrayDatepath(パス文字列を正規化)url(URL 文字列を検証)- 列挙型 (Enums):
['small', 'medium', 'large']