Search code examples
javascriptnode.jsnwjs

How to display progress bar when downloading files in nwjs


I am creating a NWJS app which needs to download some files from a url and I need to display a progress bar to display the progress of the download.

My current code just downloads the file but does not display and update a progress bar and I am wondering how this can be done.

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();
});

This just downloads the file and then changes the color of the progress bar when the download is complete. I want it to change the width of the progress bar to show the progress of the download as it is downloading.

Thanks in advance.


Solution

  • You can check the total content-length from the response to get total download size and when it returns data to data event. Finally you can get its length and can calculate the download percentage as follows:

    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();
        })
    
    });