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

129 lines
4.5 KiB
JavaScript

const { Client } = require('ssh2');
const fs = require('fs');
const path = require('path');
const config = {
host: 'hs.yifenbao.cn',
port: 22,
username: 'root',
password: 'Torch1112',
algorithms: {
kex: ['diffie-hellman-group1-sha1', 'ecdh-sha2-nistp256', 'ecdh-sha2-nistp384', 'ecdh-sha2-nistp521'],
cipher: ['aes128-ctr', 'aes192-ctr', 'aes256-ctr', 'aes128-gcm', 'aes128-cbc'],
hmac: ['hmac-sha2-256', 'hmac-sha2-512', 'hmac-sha1'],
compress: ['none', 'zlib@openssh.com', 'zlib']
}
};
const conn = new Client();
const localDir = path.join(__dirname, 'dist', 'build', 'h5');
const remoteDir = '/www/huishou/dist/build/h5';
conn.on('ready', () => {
console.log('SSH连接成功');
conn.exec(`rm -rf ${remoteDir}`, (err, stream) => {
if (err) {
console.error('删除旧目录失败:', err.message);
conn.end();
return;
}
stream.on('close', () => {
console.log('旧目录已删除');
conn.exec(`mkdir -p ${remoteDir}`, (err, stream) => {
stream.on('close', () => {
console.log('新目录已创建');
conn.sftp((err, sftp) => {
if (err) {
console.error('SFTP连接失败:', err.message);
conn.end();
return;
}
const files = [];
const scanDir = (dir) => {
const items = fs.readdirSync(dir, { withFileTypes: true });
for (const item of items) {
const fullPath = path.join(dir, item.name);
if (item.isDirectory()) {
scanDir(fullPath);
} else {
files.push(fullPath);
}
}
};
scanDir(localDir);
console.log(`共发现 ${files.length} 个文件`);
let uploaded = 0;
files.forEach(file => {
const relPath = path.relative(localDir, file);
const remotePath = `${remoteDir}/${relPath.replace(/\\/g, '/')}`;
const remoteDirPath = path.dirname(remotePath);
conn.exec(`mkdir -p ${remoteDirPath}`, (err, stream) => {
stream.on('close', () => {
sftp.fastPut(file, remotePath, {
chunkSize: 32768
}, (err) => {
if (err) {
console.error(`上传失败 ${relPath}:`, err.message);
} else {
console.log(`上传成功: ${relPath}`);
}
uploaded++;
if (uploaded === files.length) {
console.log('\n所有文件上传完成');
conn.exec('docker restart huishou', (err, stream) => {
if (err) {
console.error('重启容器失败:', err.message);
} else {
stream.on('close', () => {
console.log('容器已重启');
setTimeout(() => {
conn.exec('curl -s http://localhost:4001/h5/assets/pages-index-index*.js | grep -o "新商户" | head -5', (err, stream) => {
if (err) {
console.error('验证失败:', err.message);
} else {
let output = '';
stream.stdout.on('data', (data) => {
output += data.toString();
});
stream.on('close', () => {
console.log('\n验证结果:');
console.log(output ? '文件已包含"新商户"' : '文件不包含"新商户"');
conn.end();
});
}
});
}, 3000);
});
}
});
}
});
});
});
});
});
});
});
});
});
});
conn.on('error', (err) => {
console.error('SSH连接错误:', err.message);
});
conn.connect(config);