基于node一键发布到服务器的js脚本

const { exec } = require('child_process'); const { Client } = require('ssh2'); const scpClient = require('scp2'); const path = require('path'); const conn = new Client(); const serverConfig = { host: '192.168.3.68', port: 22, username: 'root', password: 'Fdkj@111' // 或者使用 privateKey: require('fs').readFileSync('/path/to/your/private/key') }; const localDistPath = path.resolve(__dirname, 'dist'); // 本地dist文件夹路径 const remotePath = '/home/dockerdata/nginx/www/ytkzweb'; // 远程服务器的目标文件夹路径 // 打包命令 const buildCommand = 'npm run build'; console.log('开始打包...'); exec(buildCommand, (err, stdout, stderr) => { if (err) { console.error(`Build failed: ${err.message}`); console.error(stderr); return; } conn.on('ready', () => { console.log('服务器连接成功!'); // 清空目标文件夹 conn.exec(`rm -rf ${remotePath}/*`, (err, stream) => { if (err) { console.error('Error executing command:', err); throw err; } stream.on('close', (code, signal) => { if (code !== 0) { console.error(`Failed to clear remote directory. Code: ${code}, Signal: ${signal}`); conn.end(); return; } console.log('清除远程目录成功!'); console.log('开始传输文件...'); // 传输文件 scpClient.scp(localDistPath, { host: serverConfig.host, username: serverConfig.username, password: serverConfig.password, path: remotePath }, (err) => { if (err) { console.error('Error:', err); } else { console.log('文件传输成功!'); } conn.end(); }); }).stderr.on('data', (data) => { console.error('STDERR:', data.toString()); }); // 必须要加,否则stream流的close方法不走 stream.on('data', (data) => { console.log('STDOUT:', data.toString()); }); }); }).on('error', (err) => { console.error('SSH Connection Error:', err); }).connect(serverConfig); });
上一篇:软件包管理


下一篇:使用yarn,如何编译打包electron?