Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node/Busboy: get file size

I used busboy module to parse multipart request with below coffeeScript code. The problem is, sometimes, on 'data' handler called several times for the request including one file. That means I need to sum to each size to figure the whole size. Besides the file object in the on 'file' handler seems not including size information.

How to get the whole size without calculating each part?

Thanks in advance-

busboy.on 'file', (fieldname, file, filename, encoding, mimetype) ->
  filename = "#{Meteor.uuid()}.jpg"
  dir = "#{HomeDir()}/data/profile"
  saveTo = path.join dir, filename
  file.pipe fs.createWriteStream saveTo
   files.push
     filename: filename
     path: saveTo
     fileSize: data.length
  file.on 'data', (data) ->
    # this data handler called several times 
    files.push
      filename: filename
      path: saveTo
      fileSize: data.length    
  file.on 'end', ->
    console.log 'file finished'
like image 346
kakadais Avatar asked Dec 25 '22 16:12

kakadais


2 Answers

Since you're already piping the stream to a file, you need to use something like stream-meter:

var meter = require('stream-meter');
...
busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
  ...
  var m = meter();
  file.pipe(m).pipe(fs.createWriteStream(saveTo)).on('finish', function() {
    files.push({
      filename : filename,
      path     : saveTo,
      fileSize : m.bytes,
    });
  });
});
like image 94
robertklep Avatar answered Jan 16 '23 00:01

robertklep


This is a very late response. I hope it'll help.

request.headers['content-length'] will give you the entire file size. You don't need busboy for that. It is a part of the request object and can be accessed as follows:

http.createServer(function(request, response) {

      /* request handling */

      console.log("File size:" + request.headers['content-length'] / 1024 + "KB");

      /* busboy code to parse file */

    }

An example which uses the header size info to track file transfer progress can be found at: NodeJS - file upload with progress bar using Core NodeJS and the original Node solution

EDIT:

As noted by @Matthias Tylkowski, content-length is not same as file size.

My own code has also changed since then. I noticed that in the file up-loader that I've implemented using NODEJS, I've read file size directly using HTML5 File API and passed it to the nodejs server.

like image 31
jim1427 Avatar answered Jan 16 '23 01:01

jim1427