Node.js – Buffer Length

Node.js – Buffer Length – To get Buffer length in Node.js, useBuffer.length property.

In this tutorial, we will learn how to find the length of a buffer, with the help of example programs.

Syntax

The syntax to find length of Buffer is

Buffer.length

Buffer.length returns the amount of memory allocated to the buffer in bytes.

length property of Buffer class is immutable.

ADVERTISEMENT

Example 1 – Buffer created from a string

In this example, we will use Buffer.length to find the length of a Buffer, and then print the length to console.

buffer-length.js

const buf = Buffer.from('welcome to learn node.js');
var len = buf.length
console.log(len)

Output

$ node buffer-length.js 
24

When buffer is created from the supplied string, it allocates those number of bytes as that of in the string, to the buffer.

Example 2 – Buffer created using alloc() method

In this example, buffer is allocated a specific number of bytes, and then data(not the size of buffer) is written to the buffer. We shall see what Buffer.length returns for this buffer.

buffer-length.js

const buf = Buffer.alloc(50);
const bytesWritten = buf.write('welcome to learn node.js');
var len = buf.length
console.log(len)

Output

$ node buffer-length.js 
50

It does not matter how many bytes you have overwritten from the allocated memory of buffer, but Buffer.length always returns the number of bytes allocated to the Buffer.

Conclusion

In this Node.js Tutorial, we have learnt to find the length of Buffer in Node.js.