ssh2-sftp-client前端部署工具
npm install ssh2-sftp-client
在项目目录中创建upload文件夹,action.js主要处理打包和上传打包好的文件操作、source.js主要配置需要打包的服务器地址数组对象
![](https://i-blog.csdnimg.cn/blog_migrate/356d286786654bc2de7d12b503ea1ce8.png)
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
![](https://i-blog.csdnimg.cn/blog_migrate/3a3b55fab267bb8b9a85d04a4bd7579b.png)