前端自动化打包部署服务器

ssh2-sftp-client前端部署工具

npm install ssh2-sftp-client

在项目目录中创建upload文件夹,action.js主要处理打包和上传打包好的文件操作、source.js主要配置需要打包的服务器地址数组对象

source.js
module.exports= [
    {
        ip: "xxxxxx", // 服务器地址
        username: "xxx", // 服务器 用户名
        port:"xxx",      //服务器端口
        password: "xxxxxx", // 服务器密码
        path: '/xxx/xxx/', // 操作开始文件夹 可以直接指向配置好的地址
        rmpath: '/xxx/xxx/' // 需要删除的文件夹,
    }
];
action.js
/* eslint-disable no-unused-vars */
const source = require('./source.js');//引入需要打包地址的数组对象
const shell = require("shelljs");//引入shelljs进行编译打包操作
const path = require('path');
const Client = require('ssh2-sftp-client');

//利用shelljs进行自动打包
const compilePackge = () => {
    if (shell.exec(`npm run build`).code === 0) {//执行package.json中的打包命令
        console.log("打包成功");
        return 1;
    }else{
        console.log("打包失败");
        return 0;
    }
};
//连接服务器
function connectServer() {
    source.map(item => {
        /*
        * 1.连接服务器
        * 2.备份服务器需要打包的文件,防止出错
        * 3.删除服务器先有需要打包的文件
        * 4.上传打包好的文件
        * 5.断开连接
        * */
        const sftp = new Client();
        sftp.connect({
            host: item.ip,
            port: item.port,
            username: item.username,
            password: item.password
        }).then((res) => {
            console.log(`连接成功,准备开始备份服务器文件`);
            //需要提前创建好backupfiles文件夹,否则会报错
            // eslint-disable-next-line no-undef
            return sftp.downloadDir(item.path, path.resolve(__dirname, `../backupfiles/${item.ip}`));
        }).then((res) => {
            console.log(res);
            console.log(`备份完成,准备开始删除服务器文件`);
            return sftp.rmdir(item.rmpath, true);
        }).then((res) => {
            console.log(res);
            console.log(`删除完成,准备开始上传文件至服务器`);
            // eslint-disable-next-line no-undef
            return sftp.uploadDir(path.resolve(__dirname, '../dist'), item.path);
        }).then((res) => {
            console.log(`上传完成`);
            // eslint-disable-next-line no-undef
            sftp.end();
        }).catch(err => {
            console.log(err, `上传至${item.ip}服务器失败`);
            sftp.end();
        });
    });
}
function action() {
    const compile=compilePackge();
    if(compile){
        connectServer();
    }
}
action();
package.json

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值