1. 程式人生 > >electron使用nodejs實現檔案流式下載並顯示進度

electron使用nodejs實現檔案流式下載並顯示進度

electron作為一種js編寫跨平臺桌面客戶端的技術,目前已經使用比較廣泛了,但有時候需要在軟體裡面進行內部檔案下載實現熱更新,electron自帶的autoupdate模組並不能滿足要求,所以就需要自己定製了,本文使用nodejs實現了一個簡單的模組,效果還行

模組實現

StreamDownload.js

import * as path from 'path';
import * as fs from 'fs';

const request = require('request');

// ---- 下載類 ---- //
function StreamDownload() {
// 宣告下載過程回撥函式 this.downloadCallback = null; } // 下載進度 StreamDownload.prototype.showProgress = function (received, total) { const percentage = (received * 100) / total; // 用回撥顯示到介面上 this.downloadCallback('progress', percentage); }; // 下載過程 StreamDownload.prototype.downloadFile = function (patchUrl, baseDir, callback)
{
this.downloadCallback = callback; // 註冊回撥函式 const downloadFile = 'update.7z'; // 下載檔名稱,也可以從外部傳進來 let receivedBytes = 0; let totalBytes = 0; const req = request({ method: 'GET', uri: patchUrl }); const out = fs.createWriteStream(path.join(baseDir, downloadFile)); req.pipe(out); req.on('response'
, (data) => { // 更新總檔案位元組大小 totalBytes = parseInt(data.headers['content-length'], 10); }); req.on('data', (chunk) => { // 更新下載的檔案塊位元組大小 receivedBytes += chunk.length; this.showProgress(receivedBytes, totalBytes); }); req.on('end', () => { console.log('下載已完成,等待處理'); // TODO: 檢查檔案,部署檔案,刪除檔案 this.downloadCallback('finished', percentage); }; const StreamDownload = new StreamDownload(); export default StreamDownload;

呼叫

先把模組import進來

// 定義回撥函式
function downloadFileCallback(arg, percentage)
{
    if (arg === "progress")
    {
        // 顯示進度
    }
    else if (arg === "finished")
    {
        // 通知完成
    }
}

// 呼叫下載
StreamDownload.downloadFile("http://mywebsite/update.7z", "./file", downloadFileCallback)

應用場景

  • 補丁以及擴充套件包自動更新
  • 下載管理軟體內部檔案