用Node.js很容易创建一个CLI工具

我想做的事情

我想用Nodejs创建一个不需要太复杂的CLI工具!因此我想使用cac来实现它。

我想根据这篇文章中创建的项目继续进行。

添加package和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 -> 主要.js

我们将在之前的文章中操作export.js和restore.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()

恢复.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。

广告
将在 10 秒后关闭
bannerAds