Files
huishou/git-deploy.js
T
2026-07-27 14:07:26 +08:00

104 lines
2.8 KiB
JavaScript

const { Client } = require('ssh2');
const config = {
host: 'hs.yifenbao.cn',
port: 22,
username: 'root',
password: 'Torch1112'
};
const conn = new Client();
conn.on('ready', () => {
console.log('SSH连接成功');
conn.exec('cd /www/huishou && git status', (err, stream) => {
if (err) {
console.error('执行命令错误:', err.message);
conn.end();
return;
}
let output = '';
stream.stdout.on('data', (data) => {
output += data.toString();
});
stream.stderr.on('data', (data) => {
output += data.toString();
});
stream.on('close', () => {
console.log('git状态:', output);
if (output.includes('git') && !output.includes('Not a git')) {
console.log('\n执行git pull...');
conn.exec('cd /www/huishou && git pull', (err, stream) => {
if (err) {
console.error('执行命令错误:', err.message);
conn.end();
return;
}
let pullOutput = '';
stream.stdout.on('data', (data) => {
pullOutput += data.toString();
});
stream.stderr.on('data', (data) => {
pullOutput += data.toString();
});
stream.on('close', () => {
console.log('git pull结果:', pullOutput);
console.log('\n重新构建前端...');
conn.exec('cd /www/huishou && npm run build:h5 2>&1', (err, stream) => {
if (err) {
console.error('执行命令错误:', err.message);
conn.end();
return;
}
let buildOutput = '';
stream.stdout.on('data', (data) => {
buildOutput += data.toString();
});
stream.stderr.on('data', (data) => {
buildOutput += data.toString();
});
stream.on('close', () => {
console.log('构建结果:', buildOutput.substring(0, 500));
console.log('\n重启容器...');
conn.exec('docker restart huishou', (err, stream) => {
if (err) {
console.error('执行命令错误:', err.message);
conn.end();
return;
}
stream.on('close', () => {
console.log('容器已重启');
conn.end();
});
});
});
});
});
});
} else {
console.log('不是git仓库,尝试其他方法');
conn.end();
}
});
});
});
conn.on('error', (err) => {
console.error('SSH连接错误:', err.message);
});
conn.connect(config);