进度条基于文件下载 [英] Progress bar based on file download

查看:206
本文介绍了进度条基于文件下载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何根据node webkit中下载的文件显示进度条?

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


推荐答案

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

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

此代码检查收到的数据的长度,并将其添加到 len 。按照文件的总大小划分 len ,乘以百以获得百分比。

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.

这篇关于进度条基于文件下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆