const config = require("./config.js");
const shell = require("shelljs");
const chalk = require("chalk");
const fs = require("fs");
const path = require("path");
const Client = require("ssh2-sftp-client");
const rawArgv = process.argv.slice(2);
const dayjs = require("dayjs");
// const args = rawArgv.join(" ");
// // const ora = require("ora");
const filterStage = rawArgv.includes("--prod") ? "prod" : "stage";
console.log(chalk.blue("当前环境:", filterStage));
const ClientOrg = require("ssh2").Client;
const compileDist = async () => {
if (shell.exec(`npm run build:${filterStage}`).code === 0) {
console.log(chalk.green("打包成功"));
}
};
async function connectShell(params) {
config
.filter((item) => item.nodeEnv == filterStage)
.map((item, index) => {
const sftp = new Client();
sftp
.connect({
host: item.host,
port: item.port,
username: item.username,
password: item.password,
})
.then(() => {
if (index > 0) {
return "ok";
}
console.log(
chalk.red(`${item.host}`) + chalk.blue(`---执行下拉文件备份---`)
);
console.log(chalk.blue(`---创建备份文件夹中···---`));
let newFile = `/${item.host}/${dayjs().format(
"YYYY-MM-DD"
)}/dist-${dayjs().format("HH_mm_ss")}`;
fs.mkdir(
path.resolve(__dirname, `../distbak${newFile}`),
{ recursive: true },
(err) => {
if (err) throw err;
console.log(chalk.green("---创建备份文件夹成功---"));
}
);
return sftp.downloadDir(
item.path,
path.resolve(__dirname, `../distbak${newFile}`)
);
})
.then(() => {
if (index === 0) {
console.log(
chalk.red(`${item.host}`) + chalk.blue(`---备份完成---`)
);
}
console.log(
chalk.yellow(`${item.host}`) + chalk.red(`---执行删除文件中···---`)
);
return sftp.rmdir(item.path, true);
})
.then(() => {
console.log(
chalk.red(`${item.host}`) + chalk.green(`执行删除文件成功---`)
);
console.log(
chalk.hex("#DEADED").bold(`---${item.host}执行上传文件中···---`)
);
return sftp.uploadDir(path.resolve(__dirname, "../dist"), item.path);
})
.then(() => {
console.log(
chalk.yellow(`${item.host}`) + chalk.green(`上传完成,部署成功---`)
);
sftp.end();
chmodDir(item); //赋值
})
.catch((err) => {
console.error(err, chalk.red(`${item.host}`) + chalk.red(`上传失败`));
sftp.end();
});
});
}
async function chmodDir(item) {
if (!item) {
throw "获取ip配置失败";
}
const conn = new ClientOrg();
conn
.on("ready", function () {
conn.exec("chmod 755 /etc/nginx/html -R", function (err, stream) {
if (err) throw err;
console.log(
chalk.red(`${item.host}`) + chalk.green(`---添加目录权限成功---`)
);
conn.end();
});
})
.connect({
host: item.host,
port: item.port,
username: item.username,
password: item.password,
});
}
async function runStart() {
await compileDist();
await connectShell();
}
runStart();
批量部署前端项目到多个不同的服务器
最新推荐文章于 2024-07-24 23:00:08 发布