react + electron 應用線上更新功能記錄

我喜欢喝糖水發表於2024-03-30

這個東西很多人都可能用 electron - update 這個玩意,但是我用了,發現總是更新不了,於是放棄,使用electron 自帶功能

主程序 main.js 中引入

const { autoUpdater } = require('electron-updater');
以下為主要程式碼,也是放在main.js
autoUpdater.autoDownload = false; // 禁止自動下載更新,以便更改臨時目錄
// 設定自動更新的伺服器地址
autoUpdater.setFeedURL({
provider: 'generic',
url: '', //更新的物件的路徑,這個路徑是 一個目錄路徑。目錄中包含更新的安裝包、latest.yml 檔案,其中latest.yml 檔案是打包的時候自動生成的。
serverType: 'json',
});

// 監聽更新事件
autoUpdater.on('checking-for-update', () => {
console.log('Checking for update...');
});

autoUpdater.on('update-available', (res) => {
autoUpdater.downloadUpdate();
});


autoUpdater.on('update-not-available', (res) => {
console.log('No updates available.',res);
});

autoUpdater.on('error', (error) => {
console.error('Error in auto-updater: ' + error);
});

autoUpdater.on('download-progress', (progressObj) => {
console.log('Download speed: ' + progressObj.bytesPerSecond);
console.log('Downloaded ' + progressObj.percent + '%');

});

autoUpdater.on('update-downloaded', (res) => {
dialog.showMessageBox({
type: 'info',
title:'更新提示',
message: '更新安裝包已下載,是否現在重啟安裝新版本?',
buttons: ['是', '否']
}).then((buttonIndex) => {
if (buttonIndex.response === 0) {
autoUpdater.quitAndInstall();
}
});
});
//手動觸發用的方法
function checkUpdate() {
autoUpdater.checkForUpdates();
}
以下我要補充一點。是否會檢查到更新。兩個小坑
1、package.json 中的
"version": "", 版本,一定要低於線上版本才會觸發更新,不然就會執行 autoUpdater.on('update-not-available', (res) => { ,反饋沒有更新的內容
2、關於lates.yml ,裡面是包含sha512的,安裝包可以更新之後,會對比 latest.yml 的sha512 和的對應的包的sha512 ,只有這兩個對的上才會更新成功,否則就會提示 sha512 對不上

相關文章