nwjs下载文件时如何显示进度条

How to display progress bar when downloading files in nwjs

我正在创建一个 NWJS 应用程序,它需要从 url 下载一些文件,我需要显示一个进度条来显示下载进度。

我当前的代码只下载文件,但不显示和更新进度条,我想知道如何做到这一点。

var fs = require('fs');
var https = require('https');

var file = fs.createWriteStream(filepath);

var request = https.get(fileurl, function (response) {
    response.pipe(file);
    $('#progressbar_upload').addClass('bg-success');
    uploadDone();
});

这只是下载文件,然后在下载完成时更改进度条的颜色。我希望它更改进度条的宽度以在下载时显示下载进度。

提前致谢。

您可以检查 response 中的总 content-length 以获得总下载大小以及 returns datadata 事件。最后你可以得到它的长度并可以计算下载百分比如下:

var fs = require('fs');
var https = require('https');

var file = fs.createWriteStream(filepath);

var contentLength;
var length;
var responseData = '';
var request = https.get(fileurl, function (response) {
    contentLength = parseInt(response.headers['content-length']); // in bytes
    length = [];

    // Grab the data buffer of the request
    response.on('data', (d) => {
        responseData += d;
        length.push(d.length);
        let sum = length.reduce((a, b) => a + b, 0);
        let completedParcentage = (sum / contentLength) * 100;
        console.log(`completed reading ${sum} bytes out of ${contentLength} bytes`);
        console.log(`${completedParcentage} percentage of download complete`);

        // Modify this to alter the width of progress-bar using percentageCompleted
        $('#progressbar_upload').addClass('bg-success');
    });

    response.on('end', () => {
        file.write(responseData);
        uploadDone();
    })

});