Node.js Buffer Length Using Buffer.length
In Node.js, the length property of a Buffer returns the size of that Buffer in bytes. Use buf.length when you want to know how many bytes are allocated for a specific Buffer object.
This is different from JavaScript string length. A string length counts UTF-16 code units, while a Buffer length counts bytes. For ASCII text, these values are often the same. For Unicode characters, they may be different.
In this tutorial, we will learn how to find the length of a Buffer in Node.js, how Buffer.length behaves for buffers created from strings and allocated memory, and when to use Buffer.byteLength() instead.
Buffer.length Syntax in Node.js
The syntax to find length of Buffer is
Buffer.length
In actual programs, you usually read this property from a Buffer variable.
bufferObject.length
Buffer.length returns the amount of memory allocated to the buffer in bytes.
The length value is based on the Buffer size. If a Buffer is allocated with 50 bytes, its length is 50, even if you write only a few characters into it.
The length property of a Buffer object represents the fixed byte length of that Buffer. To use a different size, create a new Buffer with the required number of bytes.
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.
The string in this example contains only ASCII characters. Each ASCII character uses one byte in UTF-8 encoding, so the Buffer length is 24 bytes.
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.
In this program, buf.write() writes data into the existing 50-byte Buffer. It does not resize the Buffer. Therefore, buf.length remains 50.
Buffer.length vs Buffer.byteLength() in Node.js
Use buf.length when you already have a Buffer and want its allocated size in bytes. Use Buffer.byteLength(string, encoding) when you have a string and want to know how many bytes that string will require in a specific encoding.
| Expression | Used for | Returns |
|---|---|---|
buf.length | An existing Buffer | Number of bytes in the Buffer |
Buffer.byteLength(str) | A string or string-like value | Number of bytes required to encode the value |
str.length | A JavaScript string | Number of UTF-16 code units, not bytes |
The difference is important when the text contains non-ASCII characters.
const text = 'café';
const buf = Buffer.from(text, 'utf8');
console.log(text.length);
console.log(Buffer.byteLength(text, 'utf8'));
console.log(buf.length);
Output
4
5
5
Here, the string has 4 characters, but the UTF-8 encoded Buffer uses 5 bytes because the character é takes more than one byte.
Getting the Actual Written Bytes in an Allocated Buffer
If you allocate a Buffer first and then write data into it, buf.length gives the total capacity of the Buffer, not the number of meaningful bytes written. To know how many bytes were written, use the return value of buf.write().
const buf = Buffer.alloc(20);
const written = buf.write('Node.js');
console.log(buf.length);
console.log(written);
Output
20
7
The Buffer has 20 bytes of allocated space, but only 7 bytes were written by the string Node.js.
Reading Only the Used Part of a Node.js Buffer
When a Buffer is larger than the data written into it, use the byte count returned by write() to slice the used part of the Buffer.
const buf = Buffer.alloc(20);
const written = buf.write('Node.js');
const usedBuffer = buf.subarray(0, written);
console.log(usedBuffer.toString());
console.log(usedBuffer.length);
Output
Node.js
7
This approach is useful when you are working with file data, network data, or binary protocols where the allocated Buffer may be larger than the actual data currently stored in it.
Choosing a Buffer Size in Node.js Programs
The correct Buffer size depends on what you are storing or reading. For text conversion, you can calculate the required byte size with Buffer.byteLength(). For file or stream processing, applications commonly work with chunks rather than loading all data into one large Buffer.
When you know the exact number of bytes, allocate that size. When you do not know the size, read data in chunks, collect only what you need, or let Node.js stream APIs manage chunked reading.
Common Mistakes with Buffer.length
- Do not use
string.lengthto calculate byte size for Unicode text. - Do not assume
buf.lengthmeans the number of bytes actually written afterBuffer.alloc(). - Do not expect
buf.write()to resize an existing Buffer. - Do not allocate a very large Buffer unless the program really needs that much memory.
- Use
Buffer.byteLength()before creating a Buffer when you need the byte size of a string.
Node.js Buffer Length FAQs
What does Buffer.length return in Node.js?
Buffer.length returns the number of bytes in an existing Buffer. If the Buffer was created with Buffer.alloc(50), its length is 50 bytes.
What is the difference between Buffer.length and Buffer.byteLength()?
Buffer.length is used on a Buffer object and returns its byte size. Buffer.byteLength() is used to calculate how many bytes a string will take when encoded.
How do I get the actual size of data written into a Buffer?
Use the return value of buf.write(). It tells you how many bytes were written. You can then use buf.subarray(0, bytesWritten) to work with only the used part of the Buffer.
Why is string.length different from Buffer.length?
string.length counts UTF-16 code units in a JavaScript string. Buffer.length counts bytes. For characters outside simple ASCII, the byte count can be larger than the string length.
Can I change the length of an existing Buffer?
No. A Buffer has a fixed size after it is created. To use a different length, create a new Buffer and copy or write the required data into it.
Editorial QA Checklist for Node.js Buffer Length
- Confirm that
buf.lengthis described as byte length, not character count. - Check that examples using
Buffer.alloc()explain allocated size versus written data. - Use
Buffer.byteLength()when explaining string-to-byte size conversion. - Keep output examples separate from JavaScript syntax examples.
- Verify that Unicode examples mention encoding, especially UTF-8.
Summary: Finding Buffer Size in Node.js
In this Node.js Tutorial, we have learnt to find the length of Buffer in Node.js.
Use buf.length to get the allocated size of an existing Buffer in bytes. Use Buffer.byteLength() when you need to calculate the byte size of a string before creating or writing to a Buffer.
TutorialKart.com