Progress bar based on file download

2020-06-06 05:52发布

问题:

How would I display a progress bar based on file downloaded in node webkit?

var https = require('https');
var fs = require('fs');
var exec = require('child_process').exec;

var file = fs.createWriteStream("update_setup.exe");
var len = 0; 
var request = https.get(url + 'appdata/update_setup.exe', function (response) {
  response.pipe(file);
  response.on('data', function (chunk) {
    file.write(chunk);
    len += chunk.length;
    var percent = (len / response.headers['content-length']) * 100;
  });
  file.on('finish', function () {
    setTimeout(function () { win.close(); exec('update_setup.exe'); }, 1000);
  });
});

回答1:

Read the content-length header of the response and compare it to the amount of bytes that have already been downloaded.

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

var file = fs.createWriteStream('dest');
var len = 0;

http.get(url, function(res) {
  res.on('data', function(chunk) {
    file.write(chunk);
    len += chunk.length;

    // percentage downloaded is as follows
    var percent = (len / res.headers['content-length']) * 100;
  });
  res.on('end', function() {
    file.close();
  });
  file.on('close', function() {
    // the file is done downloading
    exec('update_setup.exe');
  });
});

This code checks the length of the data received and adds it to len. Divide len by the file's total size and multiply by a hundred to get a percentage.