electron-updater是一个用于Electron应用程序的自动更新模块。它提供了一种简单的方式来实现electron应用程序的自动更新,使用户可以方便地获取和安装最新版本。
开发环境下,我们配置好服务器资源,自动检测更新等事件监听后,需要测试能不能正常检测到新版本以及下载安装新版本等,但是开发环境下没有打包不会触发检查更新,所以我们可以通过修改electron下app模块的isPackaged属性,来实现在开发环境下检查更新。
// 主进程
const { app } = require('electron')
const autoUpdater = require("./autoUpdater")
Object.defineProperty(app, 'isPackaged', {
get() {
return true;
}
})
app.whenReady().then(() => {
createWindow()
// 处理更新相关逻辑
autoUpdater()
})
autoUpdater.js中在开发环境还需要设置更新源的URL,它告诉autoUpdater从哪里获取更新信息和安装包,因为没有打包,所以不会读取electron-builder.yml或package.json中对应的更新配置,生产环境可以设置,也可以不用设置。
// autoUpdater.js
const { dialog } = require('electron')
const { autoUpdater } = require('electron-updater')
//自动下载更新
autoUpdater.autoDownload = false
//退出时自动安装更新
autoUpdater.autoInstallOnAppQuit = false
module.exports = () => {
// 设置更新源url
autoUpdater.setFeedURL('http://127.0.0.1:4000/')
//检查是否有更新
autoUpdater.checkForUpdates()
//有新版本时
autoUpdater.on('update-available', (_info) => {
console.log('有新版本')
dialog.showMessageBox({
type: 'warning',
title: '更新提示',
message: '有新版本发布了',
buttons: ['更新', '取消'],
cancelId: 1
}).then(res => {
if (res.response == 0) {
//开始下载更新
autoUpdater.downloadUpdate()
}
})
})
//没有新版本时
autoUpdater.on('update-not-available', (_info) => {
console.log('没有更新')
})
//更新下载完毕
autoUpdater.on('update-downloaded', (_info) => {
//退出并安装更新
autoUpdater.quitAndInstall()
})
//更新发生错误
autoUpdater.on('error', (_info) => {
console.log('更新时发生错误');
})
// 监听下载进度
autoUpdater.on('download-progress', (progress) => {
console.log(`更新进度,${JSON.stringify(progress)}`)
})
}