前端自动化部署

利用ssh实现前端自动化部署

1,在package.json新加命令

"publish-sit": "node build/publish.js sit",
"publish-prod": "node build/publish.js prod"

2,安装依赖

npm install ssh2-sftp-client

3,在build里面新加publish.js

//部署包自动上传脚本
var dayjs = require('dayjs');
const Client = require('ssh2-sftp-client');
const node_ssh = require('node-ssh');
const path = require('path');

//=======================================配置信息============================================
const sitArgList = [
  {
    remote: {
      host: '', //服务器ip
      username: '', //服务器登录名
      port: 0000, //ssh端口
      password: '' //服务器登录密码
    },
    backupDir: '', //备份文件路径
    packageDir: '', //打包文件上传路径
    backupName: '' + dayjs().format('YYYY-MM-DD-HH-mm-ss'), //备份文件名称
    distDir: path.resolve(__dirname, '../dist') //本地打包文件路径
  }
];
const prodArgList = [
  {
    remote: {
      host: '', //服务器ip
      username: '', //服务器登录名
      port: 0000, //ssh端口
      password: '' //服务器登录密码
    },
    backupDir: '', //备份文件路径
    packageDir: '', //打包文件上传路径
    backupName: '' + dayjs().format('YYYY-MM-DD-HH-mm-ss'), //备份文件名称
    distDir: path.resolve(__dirname, '../dist') //本地打包文件路径
  }
];
const argList = process.argv[2] === 'prod' ? prodArgList : sitArgList;
//===================================================================================

class Publish {
  constructor(args) {
    this.args = args;
    this.sftp = new Client();
    this.ssh = new node_ssh();
  }
  doPublish() {
    this.initBackupDir();
  }
  /**
   * 初始化备份目录
   */
  initBackupDir() {
    let _this = this;
    this.sftp
      .connect(this.args.remote)
      .then(() => {
        // return sftp.exists("/wechat/file/wxbank");
        return _this.sftp.exists(this.args.backupDir);
      })
      .then(data => {
        if (!data) {
          console.log('没有备份文件夹,创建备份文件夹');
          _this.sftp.mkdir(this.args.backupDir).then(() => {
            _this.doBackUp();
          });
        } else {
          console.log('备份文件夹已存在');
          _this.doBackUp();
        }
      })
      .catch(err => {
        console.error('检查备份文件出现异常' + err.message);
        _this.sftp.end();
      });
  }

  /**
   * 执行备份操作
   */
  doBackUp() {
    let _this = this;
    _this.sftp
      .exists(this.args.packageDir)
      .then(data => {
        console.log('备份' + data);
        console.log('源文件' + this.args.packageDir);
        console.log('目标文件' + this.args.backupDir + this.args.backupName);
        if (data === 'd') {
          _this.sftp
            .rename(this.args.packageDir, this.args.backupDir + this.args.backupName)
            .then(() => {
              console.log('备份成功');
              _this.sftp.end();
              _this.doUpload();
            })
            .catch(err => {
              console.error('备份出现异常' + err.message);
              _this.sftp.end();
            });
        } else {
          _this.sftp.end();
          _this.doUpload();
        }
      })
      .catch(err => {
        console.error('备份出现异常' + err.message);
        _this.sftp.end();
      });
  }

  /**
   * 执行上传操作
   */
  doUpload() {
    const failed = [];
    const successful = [];
    this.ssh
      .connect(this.args.remote)
      .then(res => {
        console.log('开始上传====');
        console.log('上传 源文件目录:' + this.args.distDir);
        console.log('上传 目标文件目录:' + this.args.packageDir);
        this.ssh
          .putDirectory(this.args.distDir, this.args.packageDir, {
            recursive: true,
            concurrency: 1, //TODO:此处如果并发,就容易出现上传失败的情况,所以暂时单线程上传
            validate: function (itemPath) {
              //可以增加校验器
              return true;
            },
            tick: function (localPath, remotePath, error) {
              if (error) {
                failed.push(localPath);
              } else {
                successful.push(localPath);
              }
            }
          })
          .then(status => {
            console.log('上传结束====' + status ? 'successful' : 'unsuccessful');
            if (failed.length > 0) console.error('上传失败的列表为:\n', failed.join(', \n'));
            if (successful.length > 0) console.log('上传成功的列表为:\n', successful.join(', \n'));
            this.ssh.dispose();
          })
          .catch(err => {
            console.log('上传出现异常:' + err.stack);
            this.ssh.dispose();
          });
      })
      .catch(err => {
        console.error('上传出现异常' + err.message);
        this.ssh.dispose();
      });
  }
}
for (let i = 0; i < argList.length; i++) {
  let arg = argList[i];
  let publish = new Publish(arg);
  publish.doPublish();
}

4,更新部署路径,账号,密码,备份路径

5,npm run build 后 npm run publish-sit或者npm run publish-prod径

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值