やりたいこと
そこまで凝ったことをしないCLIツールをNodejsで作りたい!
そこでcacを使ってそれを実現したいと思います。
こちらの記事で作成したプロジェクトを元に進めたいと思います。
パッケージとindex.jsの追加
$ npm i cac
$ touch index.js
cacの基本
constcli=require('cac')()cli.command('command','説明')// コマンド.option('--opt','説明')// 引数オプション.action((options)=>{// 実行したい処理console.log(options)// 引数の値をオブジェクトで受け取れる})cli.help()cli.parse()
ここまで書いたら、以下を実行することで確認出来る。
$ node index.js --help
さらにコマンドも実行できる。
以下のように変更します。
constcli=require('cac')()constexec=require('child_process').execcli.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.js
とrestore.js
を操作する処理を記述していきます。
追加したindex.js
に追記していきます。
constcli=require('cac')()constexec=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」を指定してください')}elseif(!options.bucket){console.log('「--bucket」オプションを指定してください')}elseif(!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'functionexecRestore(bucketName,tableName){constRestore=require('dynamodb-backup-restore').Restoreletconfig={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を導入することが出来ました。