electron使用nodejs实现文件流式下载并显示进度

https://ourcodeworld.com/articles/read/228/how-to-download-a-webfile-with-electron-save-it-and-show-download-progress

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)

应用场景

  • 补丁以及扩展包自动更新
  • 下载管理软件内部文件
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值