因业务需求,需要将PC网页端转化成桌面端应用,但是发布新代码后,用户已经下载的无法使用最新版本,现用简单方法实现
1.新建vue版本号
可在项目目录新建一个版本管理文件,配置基本信息,需后台配置数据库版本表,用户登陆之后检查当前版本是否为最新版本,否之则提示用户进行更新
{
"name": "electron",
"version": "1.0.1",
"description": "桌面端"
}
<script>
const version = require("../../../../public/version.json")
export default {
name: 'RuoYiDoc',
data() {
return {
update: "1.0.1",
isNew: false,
islaoding: false
}
},
created() {
this.checkVersion()
},
methods: {
checkVersion() {
if(version.version < this.update) {
this.isNew = true
}else{
this.isNew = false
}
},
updateClick() {
console.log(version);
if(this.isNew) {
this.$confirm('当前有新版本,点击更新', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
if (window.ipcRenderer) {
// 用过与Electron ipcRenderer通信 发送更新事件 分为客户端与进程端
ipcRenderer.send('update',this.update)
// 接收到updateStart事件,提示正在更新 laoding加载中
ipcRenderer.on('updateStart', (event, data) => {
if(data == 200) {
this.islaoding = true
}
});
// 下载完成接收到updateFinish事件,提示用户刷新页面,避免页面缓存 此时dist文件已经更换为最新包
ipcRenderer.on('updateFinish', (event, data) => {
console.log(data);
if(data == 'finish') {
this.islaoding = false
this.$confirm('版本更新完成,点击确定刷新页面', '提示', {
confirmButtonText: '确定',
type: 'warning',
showClose: false,
showCancelButton: false
}).then(() => {
window.location.reload()
})
}else if(data == 'error') {
this.$confirm('版本更新发生错误,请联系管理员', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning',
})
}
});
}else{
this.$modal.msgSuccess("当前不为客户端");
}
})
}else{
this.$modal.msgSuccess("当前为最新版本");
}
},
loadingClick() {
this.$modal.msgSuccess("正在更新中,请稍后");
}
}
}
</script>
2.Electron main.js更新操作
npm install compressing 安装依赖 解压文件 ,注意ipcMain.on 放在初始化createWindow里,这里可通过请求后端数据库表获取到最新下载地址
const { app, BrowserWindow,ipcMain,dialog } = require('electron')
const compressing = require('compressing');
// 监听到渲染端的更新请求,下载新文件,替换旧版本
ipcMain.on("update", (event, data) => {
var isloading = false
console.log(data);
https.get('https://mp-16ec6b41-0c2c-4640-89e3-db15e0.cdn.bspapp.com/dist.zip',async (res) => {
console.log(res.statusCode);
await event.reply('updateStart', res.statusCode);
const file = await fs.createWriteStream(`dist.zip`);
await res.pipe(file);
await file.on('finish', () => {
file.close();
console.log(`File downloaded!`);
// console.log(file);
gunzip().then(res => {
event.reply('updateFinish', 'finish');
}).catch(err => {
event.reply('updateFinish', 'error');
})
});
res.on('data', (d) => {
// console.log(d);
});
}).on('error', (error) => {
console.error(error);
});
});
// 下载的压缩包替换本地dist前端文件
function gunzip () {
return new Promise((reslove,reject) => {
compressing.zip.uncompress(path.join(__dirname, './dist.zip'), path.join(__dirname, './')).then(() => {
reslove()
}).catch(err => {
reject()
console.log(err);
});
})
}