LoginSignup
0
0

More than 1 year has passed since last update.

[Node.js] コマンドライン引数の取得

Last updated at Posted at 2021-10-15

コマンドライン引数の取得

Node.jsプログラムからコマンドライン引数を取得するには、processオブジェクトのprocess.argvプロパティを参照する。processオブジェクトはnode.jsの実行環境のグローバル変数の1つであるため、モジュールをrequireで読み込む必要がない。また、process.argvは、文字列配列になっている。

sample.js
for(let i = 0; i < process.argv.length; i++){
     console.log('argv[' + i + '] = ' + process.argv[i]);
}

上記の「sample.js」に引数を指定して実行すると以下の結果となる。

実行結果
$ node sample.js red green blue
argv[0] = C:\Program Files\nodejs\node.exe
argv[1] = C:\work\workspace\sample.js
argv[2] = red
argv[3] = green
argv[4] = blue

これより、argv[0]、argv[1]の要素にはnodeコマンドと実行されるスクリプトのファイルパス、argv[2]以降の要素にコマンドライン引数が格納されている

「npm run」でのコマンドライン引数

さらに、「npm run」で実行する場合についてもあわせて紹介する。
まず、任意のスクリプトを「npm run」で実行する場合、package.jsonのscriptsプロパティでスクリプトを定義しておく必要がある。これにより「npm run <スクリプト名>」で実行できるようになる。

package.json
"scripts":{
    "sample": "node sample.js"
}

この場合、sample.jsの実行時に引数を渡す場合は以下のように、スクリプト名の後に引数を指定する。

$ npm run sample red green blue
0
0
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
0