Bye Bye Moore

PoCソルジャーな零細事業主が作業メモを残すブログ

nodeでコマンドライン引数を扱う「argv」

argvはnodeアプリでコマンドライン引数ARGVを扱うライブラリ……って名前まんまですね。

実際のところ

導入

$ npm i argv

つかいかた

前回参照したanitubeからスクリプトを抜粋すると……こんな感じで使う子のようです。

var argv = require('argv'),

argv.option({
    name: 'year',
    short: 'y',
    type: 'number',
    description: 'broadcasted year.'
});

argv.option({
    name: 'noTitle',
    short: 'n',
    type: 'boolean',
    description: 'if true, output without title.'
});

argv.option({
    name: 'server',
    short: 's',
    type: 'boolean',
    description: 'if true, open preview webpage.'
});

var args = argv.run();

var YEAR = args.options.year || (new Date()).getFullYear(),
    NOTITLE = args.options.noTitle,
    SERVER = args.options.server;

console.log(args);

これを試しに実行すると

$ node sample.js -y 2014 -n
{ targets: [], options: { year: '2014', noTitle: true } }

くっ付けても、よろしくパースしてくれます。有能。

$ node sample.js -y 2014 -sn
{ targets: [],
  options: { year: '2014', server: true, noTitle: true } }

さらにありがたい事に、デフォルトでヘルプも生成してくれます

$ node sample.js -h

Usage: sample.js [options]

	--help, -h
		Displays help information about this script
		'sample.js -h' or 'sample.js --help'

	--year, -y
		broadcasted year.

	--noTitle, -n
		if true, output without title.

	--server, -s
		if true, open preview webpage.

コマンドラインと連動するnodeアプリを作る際は色々重宝しそうです。