react + electron 应用在线更新功能记录

这个东西很多人都可能用 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 对不上
 
 
 
 
 
 
 
 
 
posted @ 2024-03-30 18:27  我喜欢喝糖水  阅读(33)  评论(0编辑  收藏  举报
我喜欢喝糖水的博客友链:股票指标编程学习