1.在vue项目目录同级 建立 client.js
client.js:
const { exec } = require("child_process")
const ssh2 = require("ssh2")
const compressing = require('compressing');
//打包
let build = exec("cd vuedemo && npm run build", null, (err) => {
if (err) throw err;
})
build.stdout.pipe(process.stdout)
build.on("exit", () => {
compress() //build完成后,执行压缩
})
//压缩
function compress() {
compressing.zip.compressDir(path.join(__dirname+"/vuedemo/dist"), path.join(__dirname+"/vuedemo/dist.zip"))
.then(() => {
console.log('compress success!');
connect()
})
.catch(err => {
console.error(err);
});
}
var localPath = path.join(__dirname+"/vuedemo/dist.zip") //本地项目打包路径
var romotePath = "/var/www/html/dist.zip" //远程服务器部署路径
//创建ssh链接
let conn = new ssh2.Client();
function connect() {
conn.on("ready", () => {
conn.sftp((err, sftp) => {
sftp.fastPut(localPath, romotePath, {}, (err, result) => {
if (err) throw err;
shell(conn)
})
})
}).connect({
host: 'xx.xx.xx.xx', //远程服务IP地址
port: 22,
username: "root",
password: "root"
})
}
function shell(conn) {
conn.shell((err, stream) => {
stream.end(`
cd /var/www/html
mv dist bak/dist.$(date "+%Y%m%d%H%M%S").bak
unzip dist.zip
rm -rf dist.zip
exit
`).on("data", data => {
console.log(data.toString());
}).on("close", () => {
conn.end()
})
})
}
2.安装 ssh2 和 compressing 模块
cnpm i shh2 compressing
3.执行 client.js脚本
node client.js
vue项目将自动完成 build 压缩 上传到远程服务器,并自动备份上一个版本到bak文件夹;