nodejsを使ってコマンドラインプログラムの簡単なフレームを書きます.

8908 ワード

誘引子
本論文ではNodejsを使って、主に次のような形のコマンドラインプログラムを実現しました.
node index -A 100 //   
node index cmd1 -C 100 -D 200 //  option    
node index cmd2 param1 param2 param3 //  argments    
node index cmd3 -E 100 -F 200 param1 param2 //    argments option    
文の中のオプトモーションの取得値はoptions.option によって取得され、option によってオプトモーション定義時に--option によって定義される.
第三者パッケージの導入
var co = require('co');
var program = require('commander');
var colors = require('colors');
  • coは同期した書き方でコールバック関数
  • を書きます.
  • コマンドラインのパラメータとオプションを解析して、アクションを実行します.
  • colorsは出力文字の色を変更し、コンソール出力を美化する
  • .
    書き込みフロー制御関数
    各コマンドについては、実行内容は異なりますが、実行フローは以下の通りとなります.
  • は、coを用いてコマンドの処理関数
  • を呼び出す.
  • 実行成功後にsuccess情報を出力し、プログラム
  • を終了する.
  • 実行失敗後にerror情報を出力し、プログラム
  • を終了する.
    var execute = function(target, args) {
      co(function*() {
        yield target.apply(this, args);
      }).then(function() {
        console.log(colors.green('[end]') + ' success');
        process.exit();
      }, function(error) {
        console.log(error);
        process.exit();
      });
    };
    
    各コマンドの処理関数を書きます.
  • コマンド処理関数は、入力としてprogramを受け取り、指定されたオプトの値を取得することができます.
  • var doMain = function*(program) {
      console.log(colors.green('[start]') + ' doMain1...');
      // do something
      console.log(program.aa);
      console.log(colors.green('[end  ]') + ' doMain1');
    };
    
  • サブコマンド1の処理関数は、入力としてオプティクスを使用して、指定されたオプトモーションの値を取得することができます.
  • var doCmd1 = function*(options) {
      console.log(colors.green('[start]') + ' doCmd1...');
      // do something
      console.log(options.cc + ',' + options.dd);
      console.log(colors.green('[end  ]') + ' doCmd1');
    };
    
  • サブコマンド2の処理関数は、入力
  • としてコマンドラインパラメータを使用する.
    var doCmd2 = function*(arg1, arg2, arg3) {
      console.log(colors.green('[start]') + ' doCmd2...');
      // do something
      console.log(arg1 + ',' + arg2 + ',' + arg3);
      console.log(colors.green('[end  ]') + ' doCmd2');
    };
    
  • サブコマンド3の処理関数は、入力としてコマンドラインパラメータとoptionsを使用して、指定されたオプトモーションの値を取得することができます.
  • var doCmd3 = function*(arg1, arg2, arg3, options) {
      console.log(colors.green('[start]') + ' doCmd3...');
      // do something
      console.log(arg1 + ',' + arg2 + ',' + arg3 + ',' + options.ee + ',' +
        options.ff);
      console.log(colors.green('[end  ]') + ' doCmd3');
    };
    
    コマンドラインのパラメータ、アウトライン、アクションを定義します.
  • マスタコマンドは、定義プログラムのバージョン、オプト情報、およびヘルプ情報を定義します.
  • program
      .version('0.0.1');
    program
      .description('  node            ')
      .option('-A, --aa ', 'XXXX .')
      .option('-B, --bb ', 'XXXX .');
    program.on('--help', function() {
      console.log('  Examples:');
      console.log('');
      console.log('    node index cmd1 -C 100 -D 200');
      console.log('    node index cmd2 param1 param2 param3');
      console.log('    node index cmd3 -E 100 -F 200 param1 param2');
      console.log('');
    });
    
  • サブコマンド定義は、各コマンドのオプトモーションと処理actionを定義し、説明情報とヘルプ情報
  • を提供する.
    program
      .command('cmd1')
      .description('   Option    ')
      .option('-C, --cc ', 'XXXX .')
      .option('-D, --dd ', 'XXXX .')
      .action(function() {
        execute(doCmd1, arguments);
      });
    program
      .command('cmd2   [arg3]')
      .description('            ')
      .action(function() {
        execute(doCmd2, arguments);
      }).on('--help', function() {
        console.log('  arg1:');
        console.log('');
        console.log('    arg1     ');
        console.log('');
      });
    program
      .command('cmd3   [arg3]')
      .option('-E, --ee ', 'XXXX .')
      .option('-F, --ff ', 'XXXX .')
      .description('          Option    ')
      .action(function() {
        execute(doCmd3, arguments);
      }).on('--help', function() {
        console.log('  arg1:');
        console.log('');
        console.log('    arg1     ');
        console.log('');
      });
    
    コマンドライン解析と実行
    program.parse(process.argv);
    
    メインプログラムフロー制御
  • メインプログラム実行フラグ
  • を設定します.
    var mainFlg = true;
    
  • がプログラムを実行する場合、サブコマンドまたはオプトモーション情報が指定されていない場合は、ヘルプ情報を出力し、メインコマンド
  • を実行しません.
    if (!process.argv.slice(2).length) {
      program.outputHelp(make_red);
      mainFlg = false;
    }
    function make_red(txt) {
      return colors.red(txt); //display the help text in red on the console
    }
    
  • プログラムを実行する場合、サブコマンドが指定されたら、サブコマンドを実行し、メインコマンド
  • を実行しません.
    var cmds = [];
    program.commands.map(function(cmd) {
      cmds.push(cmd._name);
    });
    for (var arg of process.argv.slice(2)) {
      if (cmds.indexOf(arg) >= 0) {
        mainFlg = false;
      }
    }
    if (mainFlg) {
      execute(doMain, [program]);
    }
    
    完全なプログラムファイル
    'use strict';
    var co = require('co');
    var program = require('commander');
    var colors = require('colors');
    var execute = function(target, args) {
      co(function*() {
        yield target.apply(this, args);
      }).then(function() {
        console.log(colors.green('[end  ]') + ' success');
        process.exit();
      }, function(error) {
        console.log(error);
        process.exit();
      });
    };
    var doMain = function*(program) {
      console.log(colors.green('[start]') + ' doMain1...');
      // do something
      console.log(program.aa);
      console.log(colors.green('[end  ]') + ' doMain1');
    };
    var doCmd1 = function*(options) {
      console.log(colors.green('[start]') + ' doCmd1...');
      // do something
      console.log(options.cc + ',' + options.dd);
      console.log(colors.green('[end  ]') + ' doCmd1');
    };
    var doCmd2 = function*(arg1, arg2, arg3) {
      console.log(colors.green('[start]') + ' doCmd2...');
      // do something
      console.log(arg1 + ',' + arg2 + ',' + arg3);
      console.log(colors.green('[end  ]') + ' doCmd2');
    };
    var doCmd3 = function*(arg1, arg2, arg3, options) {
      console.log(colors.green('[start]') + ' doCmd3...');
      // do something
      console.log(arg1 + ',' + arg2 + ',' + arg3 + ',' + options.ee + ',' +
        options.ff);
      console.log(colors.green('[end  ]') + ' doCmd3');
    };
    program
      .version('0.0.1');
    program
      .description('  node            ')
      .option('-A, --aa ', 'XXXX .')
      .option('-B, --bb ', 'XXXX .');
    program.on('--help', function() {
      console.log('  Examples:');
      console.log('');
      console.log('    node index cmd1 -C 100 -D 200');
      console.log('    node index cmd2 param1 param2 param3');
      console.log('    node index cmd3 -E 100 -F 200 param1 param2');
      console.log('');
    });
    program
      .command('cmd1')
      .description('   Option    ')
      .option('-C, --cc ', 'XXXX .')
      .option('-D, --dd ', 'XXXX .')
      .action(function() {
        execute(doCmd1, arguments);
      });
    program
      .command('cmd2   [arg3]')
      .description('            ')
      .action(function() {
        execute(doCmd2, arguments);
      }).on('--help', function() {
        console.log('  arg1:');
        console.log('');
        console.log('    arg1     ');
        console.log('');
      });
    program
      .command('cmd3   [arg3]')
      .option('-E, --ee ', 'XXXX .')
      .option('-F, --ff ', 'XXXX .')
      .description('          Option    ')
      .action(function() {
        execute(doCmd3, arguments);
      }).on('--help', function() {
        console.log('  arg1:');
        console.log('');
        console.log('    arg1     ');
        console.log('');
      });
    program.parse(process.argv);
    var mainFlg = true;
    if (!process.argv.slice(2).length) {
      program.outputHelp(make_red);
      mainFlg = false;
    }
    function make_red(txt) {
      return colors.red(txt); //display the help text in red on the console
    }
    var cmds = [];
    program.commands.map(function(cmd) {
      cmds.push(cmd._name);
    });
    for (var arg of process.argv.slice(2)) {
      if (cmds.indexOf(arg) >= 0) {
        mainFlg = false;
      }
    }
    if (mainFlg) {
      execute(doMain, [program]);
    }