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)
应用场景
- 补丁以及扩展包自动更新
- 下载管理软件内部文件