コマンドラインアプリや バッチ処理を 書く時に最適な node.js用ライブラリ「ygor」の紹介です。
ygorで出来ること
- コマンドライン上で実行する' 実行ファイル コマンド名 [パラメーター] ' 形式のプログラムが簡単に書ける
( * 例 : node cmd.js 実行する関数名 引数 )
ygorのインストール
ygor は node.js で開発されているライブラリなので、ターミナル上から ' npm
' 又は ' yarn
' を使ってインストールします。
# npm
npm install ygor
# yarn
yarn add ygor
ygorの使い方
ygorの特徴は、ライブラリ本体が非常にコンパクトなので APIの使い方を覚える必要が極力少なく済みます。
下のスニペットは ygorの 最低限の使い方で、" Hello World " を返す ' greet 'コマンドを作成しています。
// test.js
const ygor = require("ygor");
function hello() {
console.log("Hello World !!");
}
// コマンドの登録 ygor.task(コマンド名, 実行する関数)
ygor.task("greet", hello);
/**
* - 使い方
* node test.js greet
* - output: Hello World !!
*/
引数や、ハイフン " - " から始まるオプションにアクセスすることも簡単にできます。
// test.js
const ygor = require("ygor");
function hello(arg) {
// node test.js greet arg1
// 引数1にアクセス
console.log(arg._[0]); // arg1
// node test.js greet -o someOption
// オプション '-o' にアクセス
console.log(arg.o); // someOption
}
ygor.task("greet", hello);
ygor には ' shell
' メソッドが用意されており、コマンド内部でshellコマンドを実行する処理も簡単に書けます。
// cdコマンドでディレクトリ移動後 READMEファイルを作成
ygor.shell("cd new-dir && touch README.md");
// promiseがサポートされているので処理を繋げて書けます
ygor.shell("cd new-dir && touch README.md")
.then(() => {
// do somthing
});
' run
' メソッド を使って 処理の中で ygor で作成したコマンドを実行することも簡単です。
// test.js
const ygor = require("ygor");
function one() {
console.log("first");
}
function two() {
console.log("second");
}
// コマンドの呼び出し
function three() {
// firstコマンドを実行
ygor.run('first')
// Promiseを使って ' first ' を実行後 'second' を実行
ygor.run('first')
.then(() => {
return ygor.run('second')
})
}
// コマンドの登録
ygor.task("first", one)
.task("second", two)
.task("third", three)
// 実行
// node ygor_test.js third
// output: first first second
下のスニペットは ygor を使って、
' 指定フォルダ内の 指定拡張子の画像ファイルを ロスレス圧縮 ' するバッチ処理を書いてました。
( 使い方: node imgCmd.js ディレクトリ名 -p 拡張子 -q クオリティ値
)
// imgCmd.js * imageMagick と fs-jetpack(nodeライブラリ)が必要です
const ygor = require("ygor");
const jetpack = require("fs-jetpack");
function optimize(arg) {
// ディレクトリ
let dir = arg._[0];
// 引数にディレクトリが入っていない時の処理
if (dir === undefined) ygor.error("empty directory");
let expression;
// option '-t' ( ファイルの拡張子 )の読み取り
switch (arg.t) {
case "jpg":
case "jpeg":
case "png":
// jpg, jpeg, pngのファイルのみを許可
expression = arg.t;
break;
default:
ygor.error("invalid file type: Allowed 'jpeg','jpg','png'.");
}
// -t オプションで指定した拡張子のファイルを検索
let find = jetpack.find(dir, { matching: "*." + expression });
if (find.length !== 0) {
// クオリティ オプション (-q)
let quality = arg.q === undefined ? 90 : arg.q;
for (file of find) {
// imageMagickのコマンドを実行
ygor.shell("convert -quality " + quality + " " + file + " " + file);
// ロスレス圧縮が終わったファイルをアウトプット
console.log("done!! " + file);
} // ! for
} // ! if
} // ! optimize()
// コマンドの登録
ygor
// optimize というコマンドを登録しました
.task("optimize", optimize);
/**
* @example
* '/Users/Name/Images' 内の 'jpg' ファイルのみを クオリティ80でロスレス圧縮
* node imgCmd.js optimize /Users/Name/Images -t jpg -p 80
*/
Summary
以上が ygor の紹介でした。ライブラリ特有の作法が極力少ないので 簡単にバッチ処理や コマンドライン アプリケーションを作ることができそうです。
GitHub : shannonmoeller/ygor