前端自动发布脚本,使用nodejs ssh2模块

该文章介绍了一种方法,通过Node.js、archiver库和ssh2模块,实现Vue项目的自动化打包和发布到服务器的过程。首先安装所需依赖,然后创建release.js脚本进行文件压缩和上传,接着在package.json中添加发布脚本,最后运行npmrunrelease即可自动完成打包和发布任务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前端使用nodejs把vue项目打包后自动发布到服务器,不再求后端

1. 安装用到的依赖包

npm i ssh2 archiver -D

2. 在项目根目录创建release.js

// 自动发布脚本
const fs = require('fs');
const path = require('path');
const archiver = require('archiver');
/* ------------------ 请配置服务器信息 --- start --------------------- */
const zipName = 'dist.zip';
const remotePath = '/www/wwwroot/web/home'; // 要上传到服务器的目标路径
const distPath = './dist'; // 要压缩的文件夹路径
// 服务器配置信息
const sshConfig = {
	host: '***.***.***.***',
	port: 22,
	username: '****',
	password: '************',
};
/* ------------------ 配置服务器信息 --- end --------------------- */

const output = fs.createWriteStream(zipName); // 压缩后的文件
const archive = archiver('zip');
output.on('close', function () {
	console.log(`${archive.pointer()} total bytes`);
	console.log('archiver has been finalized and the output file descriptor has closed.');
});
archive.on('error', function (err) {
	throw err;
});
archive.pipe(output);
const directoryPath = path.join(__dirname, distPath);
archive.directory(directoryPath, false);
archive.finalize();
const Client = require('ssh2').Client;
const conn = new Client();
conn
	.on('ready', function () {
		console.log('服务器连接成功');
		conn.sftp(function (err, sftp) {
			if (err) throw err;
			const readStream = fs.createReadStream(zipName);
			const writeStream = sftp.createWriteStream(remotePath + '/' + zipName);
			readStream.pipe(writeStream);
			writeStream.on('close', function () {
				console.log(`File ${remotePath} 上传 完成`);
				// 解压
				conn.exec(`cd ${remotePath} && unzip -o ${zipName}`, function (err, stream) {
					if (err) throw err;
					stream
						.on('close', function (code, signal) {
							console.log('部署 完成');
							// 删除本地压缩包
							fs.unlinkSync(zipName);
							conn.end();
						})
						.on('data', function (data) {
							console.log('解压中: ' + data);
						});
				});
			});
		});
	})
	.connect(sshConfig);

3.打开package.json 增加发布脚本

"scripts": {
  "dev": "vite",
  "build": "vite build",
  "preview": "vite preview",
  "release": "npm run build && node release.js" // ++++ 增加发布脚本
},

4.执行

npm run release

image-20230609140819013

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值