最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - NodeJS get a count of bytes of streaming file download - Stack Overflow

programmeradmin2浏览0评论

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?

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?

Share Improve this question asked Apr 21, 2017 at 16:28 user779159user779159 9,60216 gold badges65 silver badges94 bronze badges 0
Add a comment  | 

2 Answers 2

Reset to default 15

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

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

Update #1 (Pure NodeJS solution)

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

With typings and byteLength property:

const stream: ReadStream = file.createReadStream(); 
const chunks: Buffer[] = [];
let fileSize = 0;

stream.on('data', (chunk: Buffer) => {
  fileSize += chunk.byteLength;

  chunks.push(chunk);
});

stream.once('end', () => {
  const fileBuffer = Buffer.concat(chunks);

  console.log('equal values:', fileBuffer.byteLength === fileSize);
});
发布评论

评论列表(0)

  1. 暂无评论