通过请求获取 Node.js 中的下载进度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18323152/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 15:22:02  来源:igfitidea点击:

Get download progress in Node.js with request

node.jsdownloadrequestprogress

提问by Hyman Guy

I'm creating an updater that downloads application files using the Node module request. How can I use chunk.lengthto estimate the remaining file size? Here's part of my code:

我正在创建一个使用 Node 模块下载应用程序文件的更新程序request。如何使用chunk.length来估计剩余文件大小?这是我的代码的一部分:

var file_url = 'http://foo.com/bar.zip';
var out = fs.createWriteStream('baz.zip');

var req = request({
    method: 'GET',
    uri: file_url
});

req.pipe(out);

req.on('data', function (chunk) {
    console.log(chunk.length);
});

req.on('end', function() {
    //Do something
});

采纳答案by fakewaffle

This should get you the total you want:

这应该让你得到你想要的总数:

req.on( 'response', function ( data ) {
    console.log( data.headers[ 'content-length' ] );
} );

I get a content length of 9404541

我得到的内容长度为 9404541

回答by Anja Ishmukhametova

function download(url, callback, encoding){
        var request = http.get(url, function(response) {
            if (encoding){
                response.setEncoding(encoding);
            }
            var len = parseInt(response.headers['content-length'], 10);
            var body = "";
            var cur = 0;
            var obj = document.getElementById('js-progress');
            var total = len / 1048576; //1048576 - bytes in  1Megabyte

            response.on("data", function(chunk) {
                body += chunk;
                cur += chunk.length;
                obj.innerHTML = "Downloading " + (100.0 * cur / len).toFixed(2) + "% " + (cur / 1048576).toFixed(2) + " mb\r" + ".<br/> Total size: " + total.toFixed(2) + " mb";
            });

            response.on("end", function() {
                callback(body);
                obj.innerHTML = "Downloading complete";
            });

            request.on("error", function(e){
                console.log("Error: " + e.message);
            });

        });
    };

回答by Balthazar

Using the cool node-request-progressmodule, you could do something like this in es2015:

使用很酷的node-request-progress模块,你可以在 es2015 中做这样的事情:

import { createWriteStream } from 'fs'
import request from 'request'
import progress from 'request-progress'

progress(request('http://foo.com/bar.zip'))
 .on('progress', state => {

   console.log(state)

   /*
   {
       percentage: 0.5,        // Overall percentage (between 0 to 1)
       speed: 554732,          // The download speed in bytes/sec
       size: {
         total: 90044871,      // The total payload size in bytes
         transferred: 27610959 // The transferred payload size in bytes
       },
       time: {
         elapsed: 36.235,      // The total elapsed seconds since the start (3 decimals)
         remaining: 81.403     // The remaining seconds to finish (3 decimals)
       }
   }
   */

  })
  .on('error', err => console.log(err))
  .on('end', () => {})
  .pipe(createWriteStream('bar.zip'))

回答by Rohit Pandey

If you are using "request" module and want to display downloading percentage without using any extra module, you can use the following code:

如果您正在使用“请求”模块并希望在不使用任何额外模块的情况下显示下载百分比,您可以使用以下代码:

function getInstallerFile (installerfileURL) {

    // Variable to save downloading progress
    var received_bytes = 0;
    var total_bytes = 0;

    var outStream = fs.createWriteStream(INSTALLER_FILE);

    request
        .get(installerfileURL)
            .on('error', function(err) {
                console.log(err);
            })
            .on('response', function(data) {
                total_bytes = parseInt(data.headers['content-length']);
            })
            .on('data', function(chunk) {
                received_bytes += chunk.length;
                showDownloadingProgress(received_bytes, total_bytes);
            })
            .pipe(outStream);
};

function showDownloadingProgress(received, total) {
    var percentage = ((received * 100) / total).toFixed(2);
    process.stdout.write((platform == 'win32') ? "3[0G": "\r");
    process.stdout.write(percentage + "% | " + received + " bytes downloaded out of " + total + " bytes.");
}

回答by Gabriel Llamas

I wrote a module that just does what you want: status-bar.

我写了一个模块,可以做你想做的事:status-bar

var bar = statusBar.create ({ total: res.headers["content-length"] })
    .on ("render", function (stats){
      websockets.send (stats);
    })

req.pipe (bar);

回答by Carlos Delgado

In case someone wants to know the progress without the use of other library but only request, then you can use the following method :

如果有人想在不使用其他库的情况下了解进度而只是请求,则可以使用以下方法:

function downloadFile(file_url , targetPath){
    // Save variable to know progress
    var received_bytes = 0;
    var total_bytes = 0;

    var req = request({
        method: 'GET',
        uri: file_url
    });

    var out = fs.createWriteStream(targetPath);
    req.pipe(out);

    req.on('response', function ( data ) {
        // Change the total bytes value to get progress later.
        total_bytes = parseInt(data.headers['content-length' ]);
    });

    req.on('data', function(chunk) {
        // Update the received bytes
        received_bytes += chunk.length;

        showProgress(received_bytes, total_bytes);
    });

    req.on('end', function() {
        alert("File succesfully downloaded");
    });
}

function showProgress(received,total){
    var percentage = (received * 100) / total;
    console.log(percentage + "% | " + received + " bytes out of " + total + " bytes.");
    // 50% | 50000 bytes received out of 100000 bytes.
}

downloadFile("https://static.pexels.com/photos/36487/above-adventure-aerial-air.jpg","c:/path/to/local-image.jpg");

The received_bytesvariable saves the total of every sent chunk length and according to the total_bytes, the progress is retrieven.

received_bytes变量保存每个发送块长度的总和,并根据total_bytes检索进度。