我想在下载文件时实时显示下载速度,但以下代码无效。 Speed
为整个下载返回0.0。
https.get(options, function (update) {
fileSize = (parseInt(update.headers['content-length']) / 1048576).toFixed(1);
startTime = (new Date()).getTime();
endTime = startTime;
update.on('data', function (chunk) {
file.write(chunk);
len += chunk.length;
fileDownloaded = (len / 1048576).toFixed(1);
endTime = (new Date()).getTime();
time = (endTime - startTime) / 1000;
speed = ((fileSize / time) / (1024 * 1024)).toFixed(2);
progressPercentage.html(fileDownloaded + ' MB / ' + fileSize + ' MB ' + speed + ' MB/s');
});
});
答案 0 :(得分:2)
我认为可能有更好的解决方案,但我们走了:
var startTime = (new Date()).getTime();
var downloadedLength = 0;
update.on('data', function (chunk) {
// ...
downloadedLength += chunk.length;
var now = (new Date()).getTime();
var speed = downloadedLength / (now - startTime); //bytes/second
//speed / 1024 should return in kilobytes
//...
});
编辑:
考虑使用Date.now()
代替(new Date()).getTime();
以获得更好的效果
答案 1 :(得分:0)
认为Carlos提供的答案非常好,使用Performance.now()代替(new Date())。getTime()将是更好的选择。
供参考:https://developer.mozilla.org/en-US/docs/Web/API/Performance/now