LoginSignup
0
2

More than 3 years have passed since last update.

Node.jsでコマンドラインツールを作る時にオプション引数をいい感じに扱いたい

Last updated at Posted at 2020-07-18

結論

command-line-argscommand-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'
}
0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2