JavaScript: コマンドライン引数をパースする(その2)

2026年2月16日
1 分

Commander.js という便利なライブラリを見つけた。

サンプルとして書いてみたのがこれ。

const { program } = require('commander')


program
    .option('-f, --foo', 'boolean option')
    .option('-b, --bar <string>', 'string option')
    .option('-B, --baz [string]', 'string option with default', 'hello')
    .option('-H, --hoge <strings...>', 'multiple strings option')
    .argument('<string>')

program.parse()

const options = program.opts()
const args = program.args
console.log('Options: ', options)
console.log('Arguments: ', args)

オプションや位置引数の定義がメソッドチェーンでできて、かなりすっきりと書ける。 ついでにこれだけで -h / --help オプションも作ってくれる。

$ node args_with_commander.js --help
Usage: args_with_commander [options] <string>

Options:
  -f, --foo                boolean option
  -b, --bar <string>       string option
  -B, --baz [string]       string option with default (default: "hello")
  -H, --hoge <strings...>  multiple strings option
  -h, --help               display help for command

大体見ればわかるけど、オプション名の後ろに引数が書いてない -f / --foo オプションは引数なしの、いわゆるフラグ。 -b / --bar< > で囲まれた引数は必須で、-B / --baz[ ] で囲まれてた引数は省略可能。 これは位置引数でも同じで、この例の場合は < > で囲まれているので必須。

実行例をいくつか。

$ > node args_with_commander.js good-morning --foo
Options:  { baz: 'hello', foo: true }
Arguments:  [ 'good-morning' ]

位置引数には指定した good-morning が、 オプションの foo オプションには true が設定された。 baz にはデフォルト値の hello が設定されいる。

$ node args_with_commander.js good-morning --bar BAR
Options:  { baz: 'hello', bar: 'BAR' }
Arguments:  [ 'good-morning' ]

--bar オプションには引数が必須。指定しないと次のようにエラーになる。

$ node args_with_commander.js good-morning --bar
error: option '-b, --bar <string>' argument missing

ちょっと不思議に思ったのが、引数を省略可能なオプション。次の例では --bar BAZ と引数を指定しているので、 デフォルト値が上書きされている。

$ node args_with_commander.js good-morning --baz BAZ
Options:  { baz: 'BAZ' }
Arguments:  [ 'good-morning' ]

けど、引数を省略すると、デフォルト値ではなく true になる。

$ node args_with_commander.js good-morning --baz
Options:  { baz: true }
Arguments:  [ 'good-morning' ]

こういう使い方ってあるんだろうか。

引数を <string...> という書き方をすると、複数指定できるようになる。

$ node args_with_commander.js good-morning --hoge hoge fuga piyo
Options:  { baz: 'hello', hoge: [ 'hoge', 'fuga', 'piyo' ] }
Arguments:  [ 'good-morning' ]

--hoge 自体を複数指定しても同じ。

$ node args_with_commander.js good-morning --hoge hoge --hoge fuga --hoge piyo
Options:  { baz: 'hello', hoge: [ 'hoge', 'fuga', 'piyo' ] }
Arguments:  [ 'good-morning' ]

この例では、引数はすべて文字列として得られる。 この記事では扱わないけど、整数や実数として得るための方法も用意されているようだ。

便利に使えそうなライブラリだ。