LoginSignup
7
7

More than 3 years have passed since last update.

めっちゃ簡単にNodejsでCLIツールを作る

Posted at

やりたいこと

そこまで凝ったことをしないCLIツールをNodejsで作りたい!
そこでcacを使ってそれを実現したいと思います。

こちらの記事で作成したプロジェクトを元に進めたいと思います。

パッケージとindex.jsの追加

$ npm i cac

$ touch index.js

cacの基本

const cli = require('cac')()

cli
  .command('command', '説明') // コマンド
  .option('--opt', '説明') // 引数オプション
  .action((options) => {
    // 実行したい処理
    console.log(options) // 引数の値をオブジェクトで受け取れる
  })

cli.help()

cli.parse()

ここまで書いたら、以下を実行することで確認出来る。

$ node index.js --help

さらにコマンドも実行できる。
以下のように変更します。

const cli = require('cac')()
const exec = require('child_process').exec

cli
  .command('command', '説明') // コマンド
  .option('--opt', '説明') // 引数オプション
  .action((options) => {
    // 実行したいコマンド(例でpwdコマンドを実行する)
    exec('pwd', (err, stdout, stderr) => {
      if (err) { console.log(err); }
      console.log(stdout);
    })
  })

cli.help()

cli.parse()

上記のようにしたら、node index.js commandとすることでpwdコマンドが実行されるかと思います。

index.js

それではいよいよ、前の記事で作成したexport.jsrestore.jsを操作する処理を記述していきます。
追加したindex.jsに追記していきます。

const cli = require('cac')()
const exec = require('child_process').exec

// エクスポート用のコマンド
cli
  .command('export', 'run export from DynamoDB to S3')
  .action(() => {
      exec('node export.js', (err, stdout, stderr) => {
        if (err) { console.log(err); }
        console.log(stdout);
      })
  })

// リストア用のコマンド
cli
  .command('restore', 'run restore from S3 to DynamoDB')
  .option('--bucket <name>', 'Bucket name used for import')
  .option('--table <name>', 'Table name to import')
  .action((options) => {
    if(!options.bucket && !options.table){
        console.log('「--bucket」オプションと「--table」を指定してください')
    } else if(!options.bucket){
        console.log('「--bucket」オプションを指定してください')
    } else if(!options.table){
        console.log('「--table」オプションを指定してください')
    } else {
        exec(`node restore.js ${options.bucket} ${options.table}`, (err, stdout, stderr) => {
            if (err) { console.log(err); }
            console.log(stdout);
        })
    }
  })

cli.help()

cli.parse()

restore.js

restore.jsが現在はファイルに直接バケット名とテーブル名を記述していますが、これをコマンドライン引数で処理するように変更します。

'use strict'

function execRestore(bucketName, tableName){
    const Restore = require('dynamodb-backup-restore').Restore
    let config = {
        S3Bucket:   'backups', // 必須
        S3Prefix:   bucketName, // 任意
        S3Region:   'ap-northeast-1', // 必須
        DbTable:    tableName, // 必須
        DbRegion:   'ap-northeast-1', // 必須
    }

    Restore(config)
}

// CLIからコマンドライン引数を受け取って実行する
execRestore(process.argv[2], process.argv[3])

操作方法

# exportの実行
$ node index.js export

# restoreの実行
$ node index.js restore --bucket バケット名 --table テーブル名

で無理やりCLIを導入することが出来ました。

7
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
7