46

I get files as byte buffers and cannot use fs.stat() method. So I am try to use buf.length but this length refers to the amount of memory allocated for the buffer object and not actually the content size. For example I have file with with size 22,449 bytes. buf.length returns for 39804 for it.

lor1an
  • 654
  • 2
  • 6
  • 14

1 Answers1

97

You need byteLength:

var buff = fs.readFileSync(__dirname + '/test.txt');
console.log(Buffer.byteLength(buff));

For node 0.10.21 you can try this:

Update buffer.toSTring() is unsafe, since buffers are meant to store binary data and toString() will attempt to do character encoding translation which will corrupt the binary data.

console.log(buff.toString().length);
Alicia Sykes
  • 5,997
  • 7
  • 36
  • 64
stdob--
  • 28,222
  • 5
  • 58
  • 73
  • Thank you a lot! Do you know how make it works for node 0.10.21? – lor1an Aug 18 '16 at 10:43
  • 2
    Thanks, buf.toString('ascii').length works perfect for me – lor1an Aug 18 '16 at 12:58
  • 1
    @lor1an answer works for me too. I wasn't using `fs` but another library that returned a byte array that I needed to find out the `content-length` for. – BugHunterUK Jun 28 '17 at 19:18
  • 3
    In Node v13, Buffer.byteLength() is an instance method. Also, buf.toString().length might be skewed if you have multibyte characters, e.g. `Buffer.from("€").length // is 3` – pspi Oct 25 '19 at 07:08
  • 3
    Should know that value of `Buffer.byteLength(buff)` and `buff.toString().length` may differ and it can be problematic when uploading files using `form-data`. – Gompro Sep 17 '20 at 02:59
  • divide by 1024 to get the size in kb – Deepak Jun 23 '22 at 11:09