English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

NodeJS Basic Tutorial

NodeJS Express.js

NodeJS Buffer & URL;

NodeJS MySql

NodeJS MongoDB

NodeJS File (FS)

NodeJS Others

Node.js Buffer.length

Node.js – Buffer Length

Node.js – Buffer Length – To get the buffer length in Node.js, use Buffer.length  Method.

Syntax

Buffer.length

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

The length property of the Buffer class is immutable.

Example – Buffer created from string

The following is an example of the usage of the Buffer.length method:

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

Output Result

$ node buffer-length.js  
24

When a buffer is created from the provided string, it allocates the same number of bytes as the number of bytes in the string to the buffer.

Example – Buffer created using alloc() method

In the following example, a specific number of bytes are allocated to the buffer, and then data (not the size of the buffer) is written to the buffer. We will see the Buffer.length returned by this buffer.

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

Output Result

$ node buffer-length.js  
50

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

Conclusion:

In this Node.js tutorial, we learned how to find the length of Buffer in Node.js.