tech.chakapoko.com
Home / Node.js / CLI

[Node.js]commanderでコマンドライン引数をパースする

package.json

{
  "dependencies": {
    "commander": "^6.1.0"
  }
}

commander で引数を受け取る

index.js

const program = require("commander");

program.parse(process.argv);

console.log(program.args);

実行結果

$ node index.js a b c
[ 'a', 'b', 'c' ]

commander でフラグを解析する

index.js

const program = require("commander");

program.option("--flag").parse(process.argv);

console.log(program.flag);

実行結果

$ node index.js --flag
true
$ node index.js
undefined

commander でオプションを解析する

index.js

const program = require("commander");

program.option("-t, --test <test>", "test option").parse(process.argv);

console.log(program.test);

実行結果

$ node index.js --help
Usage: index [options]

Options:
  -t, --test <test>  test option
  -h, --help         display help for command
$ node index.js -t abc
abc
$ node index.js --test abc
abc
$ node index.js --test
error: option '-t, --test <test>' argument missing
$ node index.js
undefined

commander で必須オプションを解析する

index.js

const program = require("commander");

program.requiredOption("-t, --test <test>", "test option").parse(process.argv);

console.log(program.test);

実行結果

$ node index.js --help
Usage: index [options]

Options:
  -t, --test <test>  test option
  -h, --help         display help for command
$ node index.js
error: required option '-t, --test <test>' not specified
$ node index.js --test
error: option '-t, --test <test>' argument missing
$ node index.js --test abc
abc