94 lines
2.5 KiB
JavaScript
94 lines
2.5 KiB
JavaScript
import { Client } from 'ssh2';
|
|
import fs from 'fs';
|
|
import path from 'path';
|
|
|
|
const conn = new Client();
|
|
const localDir = path.join(__dirname, 'dist', 'build', 'h5');
|
|
const remoteDir = '/www/huishou/dist/build/h5';
|
|
|
|
conn.on('ready', () => {
|
|
console.log('=== 上传构建文件 ===\n');
|
|
|
|
conn.sftp((err, sftp) => {
|
|
if (err) {
|
|
console.log('SFTP失败:', err.message);
|
|
conn.end();
|
|
return;
|
|
}
|
|
|
|
const uploadFile = (localPath, remotePath) => {
|
|
return new Promise((resolve, reject) => {
|
|
const readStream = fs.createReadStream(localPath);
|
|
const writeStream = sftp.createWriteStream(remotePath);
|
|
|
|
writeStream.on('close', () => {
|
|
console.log('上传:', localPath);
|
|
resolve();
|
|
});
|
|
|
|
writeStream.on('error', (err) => {
|
|
console.log('上传失败:', localPath, err.message);
|
|
reject(err);
|
|
});
|
|
|
|
readStream.pipe(writeStream);
|
|
});
|
|
};
|
|
|
|
const uploadDir = async (localDirPath, remoteDirPath) => {
|
|
const files = fs.readdirSync(localDirPath);
|
|
|
|
for (const file of files) {
|
|
const localFilePath = path.join(localDirPath, file);
|
|
const remoteFilePath = remoteDirPath + '/' + file;
|
|
const stats = fs.statSync(localFilePath);
|
|
|
|
if (stats.isDirectory()) {
|
|
await new Promise((resolve) => {
|
|
sftp.mkdir(remoteFilePath, true, (err) => {
|
|
if (err && err.code !== 4) console.log('创建目录:', remoteFilePath, err.message);
|
|
resolve();
|
|
});
|
|
});
|
|
await uploadDir(localFilePath, remoteFilePath);
|
|
} else {
|
|
await uploadFile(localFilePath, remoteFilePath);
|
|
}
|
|
}
|
|
};
|
|
|
|
uploadDir(localDir, remoteDir)
|
|
.then(() => {
|
|
console.log('\n上传完成');
|
|
sftp.end();
|
|
|
|
conn.exec('/www/server/nginx/sbin/nginx -s reload', (err, stream) => {
|
|
if (err) {
|
|
console.log('重启失败:', err.message);
|
|
} else {
|
|
console.log('Nginx已重启');
|
|
}
|
|
|
|
stream.on('close', () => {
|
|
conn.end();
|
|
});
|
|
});
|
|
})
|
|
.catch((err) => {
|
|
console.log('上传失败:', err.message);
|
|
sftp.end();
|
|
conn.end();
|
|
});
|
|
});
|
|
});
|
|
|
|
conn.on('error', (err) => {
|
|
console.log('连接错误:', err.message);
|
|
});
|
|
|
|
conn.connect({
|
|
host: 'hs.yifenbao.cn',
|
|
port: 22,
|
|
username: 'root',
|
|
password: 'Torch1112'
|
|
}); |