(1)腾讯云部署egg项目——egg项目准备

本文介绍了一种利用scp2包自动化部署代码到服务器的方法,通过编写JavaScript脚本,实现文件批量上传,提高了开发效率。文章详细展示了脚本的编写过程,包括文件结构设置、进度条显示及错误处理。

因为把代码推送到服务器使用winScp软件实在是太费劲了,一次两次还好但是不能次次这样搞,这一点也不符合程序员身份。我查了一下发现有人使用docker,那又得配置一堆东西,为了快速开发迭代,我们写个脚本来替我们做这件事。

第三方包

使用了scp2

代码

需要修改的文件结构如下:

├── build  				   		# 构建相关
│   └── scp.js             		# 推送到服务器
├── config                 		# 配置相关
│   └── config.default.js  		# 基础配置
└── package.json               	# package.json

scp.js

实际使用的时候更改 files 即可,自行增删想上传到服务器的文件

'use strict';
/**
 * 将指定文件发送至服务器
 * @author simorel
 */
const ora = require('ora'); // 日志打印归于一行插件件
const client = require('scp2'); // 文本发送插件
const chalk = require('chalk');
const config = require('../config/config.default')();  // 使用方法添加‘().’
const files = ['app/', 'config/', 'package.json']; // 后面加‘/’代表是上传整个文件夹

/**
 * 发送文件至腾讯云服务器类
 * @class DeployCos
 */
class DeployCos {
  constructor() {
    this.filesPath = files; // 打包后的静态资源路径,仅上传这些文件夹或文件
    this.config = config.server;
    this.total = 0; // 总文件数
    this.spinner = this._createSpinner();

    this.main();
  }

  /**
   * 创建进度条
   */
  _createSpinner() {
    let text = this._getTip(0, 0);
    return ora({
      text,
      color: 'green',
    }).start();
  }

  /**
   * 展示进度提示条
   * @param {number} index 当前文件索引
   * @param {number} sum 总文件数
   * @memberof DeployCos
   */
  _getTip(index, sum) {
    const percentage = sum === 0 ? 0 : Math.round((index / sum) * 100);
    return `Uploading to Tencent Server: ${percentage === 0 ? '' : percentage + '% '}${index}/${sum} files uploaded`;
  }

  /**
   * 获取文件路径,并上传至服务器
   * @memberof DeployCos
   */
  main() {
    this.total = this.filesPath.length;

    const promiseArr = this.filesPath.map((file, index) => {
      return this._uploadFile(file, index + 1); // 因为index从零开始,所以这里加一
    });

    Promise.all(promiseArr)
      .then(res => {
        this.spinner.succeed(); // 结束上传进度条打印
        console.log(chalk.cyan('\n  Send files to server success.\n'));
      })
      .catch(err => {
        console.log(chalk.red('\n  Send failed with errors.\n' + err));
      });
  }

  /**
   * 实际调用上传文件函数
   * @param {String} file 文件相对路径
   * @param {number} index 文件计数器
   * @memberof DeployCos
   */
  _uploadFile(file, index) {
    return new Promise((resolve, reject) => {
      client.scp(file, {
        port: 22,
        host: this.config.host,
        username: this.config.username,
        password: this.config.password,
        path: `${this.config.path}${file}`,
      }, err => {
        this.spinner.text = this._getTip(index, this.total);
        return err ? reject(err) : resolve(err);
      });
    });
  }
}

new DeployCos();

config.default.js:

实际使用的时候更改 server 即可

/* eslint valid-jsdoc: "off" */

'use strict';

/**
 * 要使用需要 `require('xxx')()`
 * @param {Egg.EggAppInfo} appInfo app info
 */
module.exports = appInfo => {
  /**
   * built-in config
   * @type {Egg.EggAppConfig}
   **/
  const config = exports = {};

  // use for cookie sign key, should change to your own and keep security
  config.keys = 'simorel';

  // add your middleware config here
  config.middleware = [];

  // add your user config here
  const userConfig = {
    // myAppName: 'egg',

    /** 腾讯云服务器 */
    server: {
      host: '***.***.***.***',
      username: '******',
      password: '******',
      path: '******',
    }    
  };

  return {
    ...config,
    ...userConfig
  };
};

package.json

在package.json脚本内添加一行 deploy, 这样可以使用 npm run deploy 推送至服务器

{
  "scripts": {
    "deploy": "node build/scp.js",
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值