Progress bar based on file download

前提是你 提交于 2019-12-04 14:27:15

问题


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.



来源:https://stackoverflow.com/questions/19286529/progress-bar-based-on-file-download

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!