
yargsとは
Node.js用のコマンドライン引数パーサーライブラリです。
Node.jsで引数を取得するには以下のように書きますが、引数がたくさんある場合や、「node example.js --age=35」のように指定したい場合には不向きです。
1 2 3 4 | const args = process.argv.slice(2) console.log(args) // node example.js aaa bbb // [ 'aaa', 'bbb' ] |
そんなときはyargsをインストールして使うと引数に名前と値を指定できて便利です。
yargsの使い方
まず「npm i yargs」でyargsをインストールします。
npm i yargs
次にJavaScriptでyargsを読み込んで、以下のように引数を取得します。
1 2 3 4 | const yargs = require( 'yargs/yargs' ) const argv = yargs(process.argv.slice(2)).help().argv console.log(`Hello, ${argv.name}! ${argv.age} years old.`) |
あとはターミナルでNode.jsを実行すれば引数を取得した結果を表示できます。
node example.js --name=Kenji --age=35 Hello, Kenji! 35 years old.
yargsの引数を必須にする設定
前述の例の場合、引数を指定し忘れると該当の引数部分がundefinedで返ります。
node example.js --name=Kenji Hello, Kenji! undefined years old.
これを防ぐにはyargsのoptionで「demandOption: true」を設定して入力必須にします。
1 2 3 4 5 6 7 8 9 10 11 12 13 | const yargs = require( 'yargs/yargs' ) const argv = yargs(process.argv.slice(2)) .option( 'name' , { description: '名前' , demandOption: true , }) .option( 'age' , { description: '年齢' , demandOption: true , }) .help().argv console.log(`Hello, ${argv.name}! ${argv.age} years old.`) |
このコードで「node example.js」を実行すると、引数がないため以下のような結果になります。
node example.js オプション: --version バージョンを表示 [真偽] --name 名前 [必須] --age 年齢 [必須] --help ヘルプを表示 [真偽] 必須の引数が見つかりません: name, age
引数がない場合はデフォルトの値を使いたい場合は、「default: 'anonymous'」のように指定します。
1 2 3 4 5 6 7 8 9 10 11 12 13 | const yargs = require( 'yargs/yargs' ) const argv = yargs(process.argv.slice(2)) .option( 'name' , { description: '名前' , default : 'anonymous' , }) .option( 'age' , { description: '年齢' , default : 'XX' , }) .help().argv console.log(`Hello, ${argv.name}! ${argv.age} years old.`) |
node example.js Hello, anonymous! XX years old.
yargsのtypeで型を設定
yargsはoptionのtypeで型を指定できます。
引数に指定する値を間違えないよう、型の指定は必ず設定しておいたほうが良いです。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | const yargs = require( 'yargs/yargs' ) const argv = yargs(process.argv.slice(2)) .option( 'name' , { description: '名前' , type: 'string' , }) .option( 'age' , { description: '年齢' , type: 'number' , }) .option( 'verbose' , { description: 'verbose' , type: 'boolean' , }) .option( 'tags' , { description: 'tags' , type: 'array' , }) .help().argv console.log(` Hello, ${argv.name}! ${argv.age} years old. verbose: ${argv.verbose} tags: ${argv.tags} `) |
node example.js --name=Kenji --age=35 --verbose --tags=foo,bar Hello, Kenji! 35 years old. verbose: true tags: foo,bar