js-opts というモジュールが使える。
npm でインストール。
^o^ > npm install opts [email protected] node_modules\opts
js-opts というモジュール名だけど、インストールするのは opts。
昨日のファイル一覧を表示するスクリプトを拡張してみた。
var fs = require('fs');
var opts = require('opts');
var ext = false;
var options = [
{ short: "v"
, long: "version"
, description: "Show version and exit"
, callback: function() { console.log("v0.1.0"); process.exit(1); }
},
{ short: "e"
, long: "ext"
, description: "Specify ext"
, value: true
, callback: function(value) { host = value; }
}
]
opts.parse(options, true);
var ext = opts.get("ext");
var dir = opts.args()[0];
fs.readdir(dir, function(err, files) {
if (err) throw err;
files = files.filter(function(file) {
return fs.statSync(file).isFile();
});
if (ext) {
var re = new RegExp(".+\." + ext + "$");
files = files.filter(function(file) {
return re.test(file);
});
}
files.forEach(function(file) {
console.log(file);
});
});
オプションをオブジェクトの配列として定義しておいて、opts.parse の引数に渡してやると、オプション解析をしてくれる。true はなんだろう?
オプションの引数は opts.get(オプション名) で取得できる。それから、解析の結果残った引数は opts.args() で配列として取得できる。
実行結果:
^o^ > node listfiles2.js --version
v0.1.0
^o^ > node listfiles2.js --help
Usage: node C:\Users\takatoh\Documents\w\nodejs\listfiles2.js [options]
Show this help message
--help
Specify ext
-e, --ext
Show version and exit
-v, --version
^o^ > node listfiles2.js .
config.json
filesize.js
get_file.js
get_file2.js
hello.js
hello.txt
httphead.js
listfiles.js
listfiles2.js
read_config.js
server.js
test_argv.js
test_url.js
^o^ > node listfiles2.js --ext js .
filesize.js
get_file.js
get_file2.js
hello.js
httphead.js
listfiles.js
listfiles2.js
read_config.js
server.js
test_argv.js
test_url.js
–help オプションは定義しなくても、自動で作ってくれるみたい。
js-opts のサイト:
cf. https://bitbucket.org/mazzarelli/js-opts/wiki/Home
[追記]
js-opts のソースを確認したところ、opts.parse の第2引数に true を指定すると、–help オプションを追加してくれるみたい。