Progress bar based on file download

久未见 提交于 2019-12-03 09:01:06

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.

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