如何根据节点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);
});
});
答案 0 :(得分: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
除以文件的总大小,再乘以100得到一个百分比。