简体   繁体   中英

useing mikeal's request when piping something,how to listen events to show progress with a progress-bar

我正在使用mikeal的请求编写模块,以便在管道传输某些东西时上传和下载文件,如何通过进度栏收听事件以显示进度,请给我一些示例,谢谢...

I did a quick search on the NPM registry and found progress , a module that shows a progress bar in the command line. It looks nice and it even has an example showing how to use it to show a download progress. I'm reproducing it here:

var ProgressBar = require('progress')
  , https = require('https');

var req = https.request({
    host: 'download.github.com'
  , port: 443
  , path: '/visionmedia-node-jscoverage-0d4608a.zip'
});

req.on('response', function(res){
  var len = parseInt(res.headers['content-length'], 10);

  console.log();
  var bar = new ProgressBar('  downloading [:bar] :percent :etas', {
      complete: '='
    , incomplete: ' '
    , width: 20
    , total: len
  });

  res.on('data', function(chunk){
    bar.tick(chunk.length);
  });

  res.on('end', function(){
    console.log('\n');
  });
});

req.end();

The code above will generate a progress bar that looks like this:

downloading [=====             ] 29% 3.7s​

Notice how he checks the content-length header to get the length of the file being downloaded and uses that to calculate the completion percentage. It then passes the progress bar the length of each chunk.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM