JavaScript: コマンドライン引数をパースする
ちょっとしたスクリプトを書こうとして調べたのでメモ。
コマンドライン引数をパースするには、Node.js の node:utl パッケージに含まれている parseArgs が使える。
const { parseArgs } = require("node:util")
const {
values,
positionals
} = parseArgs({
allowPositionals: true,
options: {
foo: {
type: "boolean",
short: "f",
},
bar: {
type: "string",
short: "b",
default: "hello",
},
baz: {
type: "string",
short: "B",
multiple: true,
},
help: {
type: "boolean",
short: "h",
}
},
})
if (values.help) {
console.log("Example for CLI parameters")
console.log("")
console.log("node args.js [option values] [positional parameters]")
console.log("")
console.log("--foo, -f boolean option")
console.log("--bar, -b string option. default to 'hello'")
console.log("--baz, -B multiple string option")
console.log("--help, -h show this message and exit")
process.exit(0)
}
console.log("Options:")
console.log(values)
console.log("Positional parameters:")
console.log(positionals)
--foo / -f はスイッチ。--bar / -b は引数をとるがデフォルト値がある。--baz / -B は複数回指定できる。
--help / -h オプションを作る専用の機能はないようなのでいささか不格好だな。
実行例:
takatoh@apostrophe:~$ node args.js hoge fuga piyo
Options:
[Object: null prototype] { bar: 'hello' }
Positional parameters:
[ 'hoge', 'fuga', 'piyo' ]
takatoh@apostrophe:~$ node args.js --foo hoge fuga piyo
Options:
[Object: null prototype] { foo: true, bar: 'hello' }
Positional parameters:
[ 'hoge', 'fuga', 'piyo' ]
takatoh@apostrophe:~$ node args.js --foo --bar hoge fuga piyo
Options:
[Object: null prototype] { foo: true, bar: 'hoge' }
Positional parameters:
[ 'fuga', 'piyo' ]
takatoh@apostrophe:~$ node args.js --foo --bar hoge --baz fuga --baz piyo
Options:
[Object: null prototype] {
foo: true,
bar: 'hoge',
baz: [ 'fuga', 'piyo' ]
}
Positional parameters:
[]
