2

如何根据节点 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);
  });
});
4

1 回答 1

1

读取content-length响应的标头并将其与已下载的字节数进行比较。

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

此代码检查接收到的数据的长度并将其添加到len. 除以len文件的总大小并乘以一百得到百分比。

于 2013-10-10T03:27:02.763 回答