NodeJSでCLIを作成するときに便利なライブラリ
先日、ちょっとしたようでNodeJSでCLIを作りました。
そこで使うと便利なライブラリを紹介します。
75lb/command-line-args
command-line-argsは、コマンドライン引数を扱いやすくするライブラリです。
const commandLineArgs = require('command-line-args')
const optionDefinitions = [
{ name: 'verbose', alias: 'v', type: Boolean },
{ name: 'src', type: String, multiple: true, defaultOption: true },
{ name: 'timeout', alias: 't', type: Number }
]
const options = commandLineArgs(optionDefinitions)
こう定義しておくだけで
$ example --verbose --timeout 1000 --src one.js two.js
といった引数をoption.timeout
といった形で使うことができます。
75lb/command-line-usage
これは先ほどのcommand-line-args
と一緒に使えるものでオプションの使い方などを出力するのに使えます。
const commandLineUsage = require('command-line-usage')
const sections = [
{
header: 'A typical app',
content: 'Generates something {italic very} important.'
},
{
header: 'Options',
optionList: [
{
name: 'input',
typeLabel: '{underline file}',
description: 'The input to process.'
},
{
name: 'help',
description: 'Print this usage guide.'
}
]
}
]
const usage = commandLineUsage(sections)
console.log(usage)
と定義することで
A typical app
Generates something very important.
Options
--input file The input to process.
--help string Print this usage guide.
といったものが出力できます。
僕はcommand-line-args
と組み合わせて
if (options.help || !options.outputDir) {
console.log(usage);
} else {
main();
}
のように定義して--help
や欲しい引数がなかったときにusageを出力するようにしています。
readline-sync
readline-syncは標準入力を簡単に実装できるライブラリです。
標準パッケージのみで標準入力を行うと結構めんどくさいのですが、
これを使うと
const hoge = readlineSync.question("Hoge: ")
のように簡単に標準入力が使えます。
よかったら使ってみてください。