electron增量更新

354 阅读1分钟

背景

  • 一开始用的是electron-updater来做的软件全量更新,软件里有不需要覆盖的文件夹
    "extraResources": [
      {
        "from": "../chrome",
        "to": "chrome"
      },
      {
        "from": "../defaultPlugin",
        "to": "LumiExtensions"
      }
    ],
  • 全量更新的话,会导致chrome和LumiExtensions文件夹会被覆盖掉

增量更新

  • 先贴代码
const { app, ipcMain, BrowserWindow } = require('electron')

const EAU = require('electron-asar-hot-updater');

ipcMain.on('asar-hot-updater', (event, arg) => {
    // 获取win
    const win = BrowserWindow.getFocusedWindow();

    console.log('开始检查asar-hot-updater更新');
    // Initiate the module
    EAU.init({
        'api': 'http://localhost:9999/update', // The API EAU will talk to
        'server': false // Where to check. true: server side, false: client side, default: true.
    });

    EAU.check(function (error, last, body) {
        if (error) {
            if (error === 'no_update_available') { return false; }
            console.log(error, '检查asar-hot-updater更新时出错');
            return false
        }

        EAU.progress(function (state) {
            win.webContents.send('download-progress', (state.percent * 100).toFixed(0));
            console.log(state, '这里是更新进度');
        })

        EAU.download(function (error) {
            if (error) {
                console.log(error, '下载asar-hot-updater更新时出错');
                return false
            }
            // 更新下载进度事件,现在代表的是下载完成,所以这里可以直接发送100
            win.webContents.send('download-progress', 100);
            console.log('下载完成');
            if (process.platform === 'darwin') {
                app.relaunch()
                app.quit()
            } else {
                app.quit()
            }
        })
    })
})
  • 网上的例子是在app.on('ready'生命周期,一启动软件就去下载,然后重启软件
  • 现在我们软件是需要手动点更新的时候去下载
  • 'api': 'http://localhost:9999/update', 这里的接口返回值里必须有version字段和asar字段,asar字段值为http://localhost:9999/update.asar asar文件的地址
  • EAU.check 这里是下载前去检查你填的这些内容是否正确
  • EAU.progress 这里是下载过程中ing
  • EAU.download 这里是下载完成