实现打包时自动将dist文件夹部署到服务器
const Ssh = require('ssh2');
const fs = require('fs');
const readline = require('readline');
let pre = 'xxx';
let packageZipName;
let sshClient = new Ssh.Client();
fs.readdir('./dist/', {}, (err, files) => {
if (err) {
console.log(err);
return;
}
packageZipName = files.find((fileName) => fileName.endsWith('zip'));
if (packageZipName) {
console.log(mode, '部署路径:', pre);
const rl = readline.createInterface(process.stdin, process.stdout);
rl.question(`> 是否部署到测试环境(y/n):`, (status) => {
rl.close();
if (status.toLowerCase() === 'y') {
console.log('开始执行上传');
uploadProject();
}
});
}
});
function uploadProject() {
sshClient
.on('ready', () => {
sshClient.sftp((err, sftp) => {
sftp.fastPut(
'./dist/' + packageZipName,
`${pre}/bak/${packageZipName}`,
{},
(err) => {
if (!err) {
deployProject(sshClient);
} else {
console.log(err);
}
}
);
});
})
.connect({
host: 'xxx',
port: 'xxx',
username: 'xxx',
password: 'xxx',
});
}
function deployProject(sshClient) {
sshClient.shell((err, stream) => {
stream
.end(
`
cd ${pre}/dist/
rm -rf *
cd ${pre}/bak/
unzip ${packageZipName} -d ${pre}/dist/
exit
`
)
.on('data', (data) => {
console.log('data: ', data.toString());
})
.on('close', () => {
console.log('close');
sshClient.end();
});
});
}
使用方式
在package.json文件中的打包命令配置以下代码
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build && node ./autoDeploy.js",
},