NodeJS获得流文件下载的字节数 [英] NodeJS get a count of bytes of streaming file download

查看:252
本文介绍了NodeJS获得流文件下载的字节数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此代码中,我从url流式传输文件并将其保存到文件中。是否有一种方法也可以通过某种方式对它进行管道传输,以计算管道传输的字节数? (哪个会告诉我文件的大小。)

In this code I stream a file from a url and save it to a file. Is there a way to also pipe it through something that will count the number of bytes piped? (Which would tell me the file size.)

  request.stream(url)
    .pipe(outputFile)

是否有一些库可以通过下载来进行下载,或者我可以通过一种简单的方式

Is there some library that would do this by piping the download through it, or a simple way for me to do it myself?

推荐答案

您可以使用 请求 库:

You can do it like this with request library:

const request = require('request');
const fs = require('fs');

var downloaded = 0;
request.get(url)
  .on('data', function(chunk){
    downloaded += chunk.length;
    console.log('downloaded', downloaded);
  })
  .pipe(fs.createWriteStream(fileName));

此外,您还可以检查此链接,以了解如何在没有 request 包的情况下进行操作。

Also, you can check this link to learn how to do it without request package.

var http = require('http');
var fs = require('fs');

var download = function(url, dest, cb) {
  var file = fs.createWriteStream(dest);
  var downloaded = 0;
  var request = http.get(url, function(response) {
    response.pipe(file);
    response.on('data', function(chunk){
      downloaded += chunk.length;
      console.log(downloaded);
    })
    file.on('finish', function() {
      file.close(cb);
    });
  });
}

这篇关于NodeJS获得流文件下载的字节数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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