Get the Length of a Buffer in Node.js

Aug 19, 2020

Node.js buffers are objects that store arbitrary binary data. Buffers have a length property that contains the number of bytes in the buffer.

const buf = Buffer.from('Hello, World', 'utf8');

buf.length; // 12, same as 'Hello, World'.length

For buffers containing UTF8 encoded strings, the buffer's length is equivalent to the length of the string. For example, if you read a text file from the file system using fs, the resulting buffer's length is the same as the number of characters in the text file.

const fs = require('fs');
fs.writeFileSync('./test.txt', 'Hello, World');

const buf = fs.readFileSync('./test.txt');

Buffer.isBuffer(buf); // true
buf.length; // 12, same as 'Hello, World'.length

Allocated vs Actual

Note that Buffer#length contains the number of allocated bytes for the buffer, not how many bytes are actually used. Often these two are equivalent, but they may be different.

For example, if you allocate a 100-byte buffer using Buffer.alloc(), the buffer's length will always be 100, regardless of the buffer's contents.

const buf = Buffer.alloc(100);

buf.length; // 100, even though the buffer contains 100 `0` bytes

// Write 'Hello, World' to the buffer starting at offset 0
buf.write('Hello, World', 0);

buf.length; // still 100, because there's 100 bytes allocated.

Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Node Tutorials