結論
command-line-args と command-line-usage を使うといい感じになる
オプション引数の説明を表示する
src/index.js
const commandLineUsage = require("command-line-usage");
const usage = commandLineUsage([
{ header: "command line tool", content: "description" },
{
header: "Options",
optionList: [
{ name: "str", description: "description of str" },
{ name: "multi", description: "ex: --multi foo --multi bar" },
{ name: "int", description: "default: 123" },
{ name: "bool", alias: "b", type: Boolean, description: "ex: -b" },
],
},
]);
console.log(usage);
出力
$ node src/index.js
command line tool
description
Options
--str string description of str
--multi string ex: --multi foo --multi bar
--int string default: 123
-b, --bool ex: -b
オプション引数の値を取得する
src/index.js
const commandLineArgs = require("command-line-args");
const args = commandLineArgs([
{ name: "str", type: String },
{ name: "multi", multiple: true, type: String },
{ name: "bool", alias: "b", type: Boolean },
{ name: "int", type: Number, defaultValue: 123 },
{ name: "def", defaultOption: true },
]);
console.log(args);
出力
$ node src/index.js --str hoge --multi foo --multi bar -b foobar
{
int: 123,
str: 'hoge',
multi: [ 'foo', 'bar' ],
bool: true,
def: 'foobar'
}