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.
Asked
Active
Viewed 5.9k times
1 Answers
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 andtoString()
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
-
-
2
-
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
-
3In 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
-
3Should 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
-