基于node一键将打包后的前端文件发布到服务器指定目录的js脚本
需要使用node的2个包
npm install ssh2 scp2
基于node进行ssh连接的控件
下面直接贴代码,已经在代码中加了注释
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);
});
注意 注意 注意
stream.on('data', (data) => {console.log('STDOUT:', data.toString());
});
这块代码,一定要加
以上