【问题标题】:Electron Auto-update WindowsElectron 自动更新 Windows
【发布时间】:2016-10-04 11:37:52
【问题描述】:

谁能帮助我从头开始描述如何在电子中使用自动更新程序。如何使用正确的软件包并编写正确的 CLI 来拥有一个在 Windows 中具有自动更新功能的简单应用。

非常感谢。

【问题讨论】:

    标签: command-line-interface packages electron auto-update


    【解决方案1】:

    请按照步骤实现electron js自动更新代码工作。

    1. npm install electron-updater(用于使用自动更新程序)
    2. npm install electron-log(这将有助于查看日志中的错误)
    3. npm install electron --save-dev
    4. npm install electron-builder --save-dev

    然后,在你的 main.js 中(你的应用程序的入口文件粘贴自动更新代码)

    const electron = require('electron');
    const url = require('url');
    const path = require('path');
    const pjson = require('../package.json')
    
    // auto update code
    const log = require('electron-log');
    const { autoUpdater } = require("electron-updater");
    autoUpdater.logger = log;
    autoUpdater.logger.transports.file.level = 'info';
    log.info('App starting...');
    let appversion = pjson.version;
    
    const { app, BrowserWindow } = electron;
    
    let homePageWindow;
    
    function sendStatusToWindow(text, ver) {
        log.info(text);
        homePageWindow.webContents.send('message', text, ver);
    }
    
    function createDefaultWindow() {
        homePageWindow = new BrowserWindow({
            minimizable: true,
            maximizable: true,
            closable: true,
        });
        homePageWindow.maximize();
        homePageWindow.webContents.openDevTools();
        //homePageWindow.setMenu(null);
    
        homePageWindow.on('closed', () => {
            homePageWindow = null;
            app.quit();
        });
    
        homePageWindow.loadURL(url.format({
            pathname: path.join(__dirname, '../webFiles/homePage.html'),
            protocol: 'file:',
            slashes: true
    
    
       }));
        return homePageWindow;
    }
    
    // auto update conditions
    autoUpdater.on('checking-for-update', () => {
        sendStatusToWindow('Checking for update...', appversion);
    })
    
    autoUpdater.on('update-available', (info) => {
        sendStatusToWindow('Update available.', appversion);
    })
    
    autoUpdater.on('update-not-available', (info) => {
        sendStatusToWindow('Update not available.', appversion);
    })
    
    autoUpdater.on('error', (err) => {
        sendStatusToWindow('Error in auto-updater. ' + err, appversion);
    })
    
    autoUpdater.on('download-progress', (progressObj) => {
        let log_message = "Download speed: " + progressObj.bytesPerSecond;
        log_message = log_message + ' - Downloaded ' + progressObj.percent + '%';
        log_message = log_message + ' (' + progressObj.transferred + "/" + progressObj.total + ')';
        sendStatusToWindow(log_message, appversion);
    })
    
    autoUpdater.on('update-downloaded', (info) => {
        setTimeout(function () {
            sendStatusToWindow('Update downloaded..Restarting App in 5 seconds', appversion);
            homePageWindow.webContents.send('updateReady');
            autoUpdater.quitAndInstall();
        }, 5000)
    });
    
    app.on('ready', function () {
        createDefaultWindow();
        autoUpdater.checkForUpdatesAndNotify();
    });
    
    app.on('window-all-closed', () => {
        app.quit();
    });
    

    参考我的代码并在你的 main.js 中进行必要的更改

    然后将应用程序的版本设置为 1.0.0 运行命令“npm run build --win -p always”生成第一个构建

    我使用 Github 来存储应用程序组件。 所以,你需要在git上上传1.0.0的app文件(latest.yml、builder-effective-config.yaml、app_setup1.0.0.exe、app_setup1.0.0.exe.blockmap文件)并为其创建一个release。将版本发布为 1.0.0

    然后将应用的版本更改为 1.0.1 运行命令“npm run build --win -p always”生成第二个构建。

    再次做github步骤——你需要在git上上传1.0.1的app文件(latest.yml、builder-effective-config.yaml、app_setup1.0.1.exe、app_setup1.0.1.exe.blockmap文件)并为它创建一个版本。将版本发布为 1.0.1

    所以现在在您的 git 项目中,您有 2 个版本 1.0.0 和 1.0.1

    现在为了测试您需要在本地计算机上运行 1.0.0 的设置的内容。因此,如果代码编写正确,您将看到以下日志 1. 可用更新 2. 更新下载及其百分比

    然后,一旦 100% 下载完成,应用会在 5 秒内重新启动(按照代码中提到的秒数),并且您的应用现在已更新。 呸呸呸呸

    【讨论】:

      【解决方案2】:

      我试过electron-basic-updater, electron-asar-updater, electron-installer-windows 等。并花了几个小时尝试如何发布/更新我的应用程序,然后使用 electron-packager 进行打包和 Squirrel 进行自动更新。他们有他们的优势。

      我假设读者具有使用 Electron 应用程序的基本知识,因此我不会深入了解基础知识。

      重要提示:您必须在 Windows 中创建一个包/安装程序并安装该应用程序才能使自动更新程序正常工作!

      在你的主app.js中,添加一个IPC来处理更新场景:

      ipcMain.on('check-for-update', function(event, arg) {
      
      /* AUTO UPDATER */
      const autoUpdater = electron.autoUpdater;
      const os = require('os');
      const {dialog} = require('electron');
      
      /* For Windows, PATH to DIRECTORY that has nupkg and RELEASES files (Windows alone) */
      /* And add "Options Indexes" to htaccess if you want listing on that dir --@thinkdj */
      
      var releaseDIR = config.webURL + '/releases/win' + (os.arch() === 'x64' ? '64' : '32');
      
      autoUpdater.setFeedURL(releaseDIR);
      
      autoUpdater
          .on('error', function(error){
              loggit(error);
              return dialog.showMessageBox(mainWindow, {
                  type: 'info',
                  icon: basePath + "/assets/refico32.ico",
                  buttons: ['Dang!'],
                  title: appName + ": Update Error",
                  message: "Something's not right out there. Please try again later.",
                  detail: "Umm... \nIt's not you, it's the server"
              });
          })
          .on('checking-for-update', function(e) {
              loggit('Checking for update at ' + releaseDIR);
          })
          .on('update-available', function(e) {
      
              var downloadConfirmation = dialog.showMessageBox(mainWindow, {
                  type: 'info',
                  icon: basePath + "/assets/refico32.ico",
                  buttons: ['Proceed'],
                  title: appName + ": Update Available",
                  message: 'An update is available. The update will be downloaded in the background.',
                  detail: "Size: ~42 MB"
              });
      
              loggit('Downloading update');
      
              if (downloadConfirmation === 0) {
                  return;
              }
      
          })
          .on('update-not-available', function(e) {
              loggit('Update not available');
              return dialog.showMessageBox(mainWindow, {
                  type: 'info',
                  icon: basePath + "/assets/refico32.ico",
                  buttons: ['Cool'],
                  title: appName + ": No update available",
                  message: "It seems you're running the latest and greatest version",
                  detail: "Woot, woot! \nTalk about being tech-savvy"
              });
          })
          .on('update-downloaded',  function (event, releaseNotes, releaseName, releaseDate, updateUrl, quitAndUpdate) {
      
              var index = dialog.showMessageBox(mainWindow, {
                  type: 'info',
                  icon: basePath + "/assets/refico32.ico",
                  buttons: ['Install Update','Later'],
                  title: appName + ": Latest version downloaded",
                  message: 'Please restart the app to apply the update',
                  detail: releaseName + "\n\n" + releaseNotes
              });
      
              if (index === 1) return;
      
              force_quit = true;
              autoUpdater.quitAndInstall();
          });
      
      
      autoUpdater.checkForUpdates();
      
      event.returnValue = "Checking for updates: " + releaseDIR + " Install Path: " + appPath;
       });
      

      附加说明: 1] 你的 app.js 必须在一开始就处理松鼠事件。您可以为 handleSquirrelEvent 编写自己的处理程序,或者只需一个简单的 if (require('electron-squirrel-startup')) return; 即可。 2] 在撰写本文时,一旦启动自动更新过程,用户就无法取消更新过程。

      为了创建您的安装程序,您的 Gruntfile.js(在npm install grunt, npm install grunt-cli 之后)应该类似于

      module.exports = function(grunt) {
          grunt.loadNpmTasks('grunt-electron-installer');
          grunt.initConfig({
              'create-windows-installer': {
              'ia32': {
                  appDirectory: "C:\\refreshie\\app\\build\\Refreshie-win32-ia32",
                  outputDirectory: "C:\\refreshie\\app\\build\\Distro\\Refreshie-Win-ia32",
                  loadingGif: "C:\\refreshie\\app\\assets\\images\\install.splash.gif",
                  iconUrl: "C:\\refreshie\\app\\assets\\refico.ico",
                  setupIcon: "C:\\refreshie\\app\\assets\\refico.ico",
                  signWithParams: "/a /f C:\\refreshie\\app\\build\\tools\\cert.signingkey.pfx /p F5",
                  noMsi: true
              }
          }
          });
          grunt.registerTask('default', ['create-windows-installer']);
      };
      

      【讨论】:

        【解决方案3】:

        目前,进行电子自动更新的最佳方法是使用电子生成器。

        npm install electron-builer –save-dev

        npm install electron-updater –save

        出于演示目的,获取 http-server 作为您的虚拟主机服务器。

        npm install http-server –save

        构建包很简单,创建两个文件夹“build”和“dist”,然后 在 package.json 脚本中添加这个并运行

        "scripts": {
           "start": "set NODE_ENV=dev&& tsc && concurrently \"npm run tsc:w\" \"electron .\" ",
           "tsc": "tsc",
           "tsc:w": "tsc -w",
             ;
           "dist": "build -w --x64",
           "wb": "http-server wwwroot/ -p 8080",
              ;
         },
        

        npm 运行分布

        对于自动更新程序,创建一个文件夹 wwwroot 并假设这是您的 Web 主机服务器并将您的网站启动为:

        npm 运行 wb

        将所有内容从 dist 文件夹复制到 wwwroot 文件夹。

        好的。

        详细代码请查看here

        【讨论】:

          猜你喜欢
          • 2016-03-11
          • 2020-01-27
          • 2018-06-08
          • 2010-09-17
          • 2017-03-10
          • 2021-03-17
          • 1970-01-01
          • 2010-12-14
          • 2010-11-08
          相关资源
          最近更新 更多