使用nw-autoupdater實現客戶端應用的自動升級
阿新 • • 發佈:2019-01-31
前段時間開發了新的需求,要求實現應用的自動檢測更新升級。由於客戶端是通過nw.js開發的,nw.js的官方文件有三種方法實現自動升級,我選擇了nw-autoupdater來實現,具體實現的原理就是:首先從遠端伺服器讀取配置檔案;檢查遠端配置檔案中的版本是否大於本地版本;如果遠端伺服器有最新版本,則下載最新程式包;將下載的安裝包解壓到一個臨時目錄,關閉應用程式啟動最新版本,重啟應用程式。
先看了一下github上的demo,https://github.com/dsheiko/nw-autoupdater,然後開始升級的嘗試了。使用node搭建了一個伺服器,模擬升級伺服器。將github上的專案下載到本地,其他檔案不動,直接對package.json檔案進行修改配置,將對應的升級包放在配置檔案中對應的位置。
接下來就是在專案中添加升級的相關邏輯了。首先在專案中下載依賴包nw-autoupdater。可以直接通過npm install nw-autoupdater –save-dev下載。然後在程式碼中新增檢測版本的方法
checkBrowserVersion: function () { const AutoUpdater = require( "nw-autoupdater" ), updater = new AutoUpdater( require( "../package.json" ) ); async function main(){ try { // Update copy is running to replace app with the update if ( updater.isSwapRequest() ) { var page = document.getElementById("homePage"); var pageLoading=document.getElementById("loadingBox"); page.style.display = "none"; pageLoading.style.display="block"; await updater.swap(); await updater.restart(); return; } // Download/unpack update if any available const rManifest = await updater.readRemoteManifest(); const needsUpdate = await updater.checkNewVersion( rManifest ); if ( !needsUpdate ) { return; } if (!confirm( $translate.instant('IDS_UPDATE_ALERT'))){ return; } // Subscribe for progress events updater.on( "download", ( downloadSize, totalSize ) => { console.log( "download progress", Math.floor( downloadSize / totalSize * 100 ), "%" ); }); updater.on( "install", ( installFiles, totalFiles ) => { console.log( "install progress", Math.floor( installFiles / totalFiles * 100 ), "%" ); }); const updateFile = await updater.download( rManifest ); await updater.unpack( updateFile ); alert( $translate.instant('IDS_UPDATE_RESTART')); updater.restartToSwap(rManifest); } catch ( e ) { console.error( e ); } } setTimeout(function () { main(); }, updater.isSwapRequest()?0:1000); }
如果不出意外的話,自動升級就可以實現了,在這裡需要注意的是,升級包必須是壓縮格式的,但不直接是最新安裝包。在osx中,升級包是直接最新版本的.app檔案壓縮;在windwos系統中,升級包是安裝成功後開啟所在資料夾根目錄下的所有檔案。