Open In App

Node.js Buffer.byteLength() Method

Last Updated : 11 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The Buffer.byteLength() method is used to return the length in bytes of the specified buffer object. 

Syntax:

Buffer.byteLength( string, encoding )

Parameters: This method accepts two parameters as mentioned above and described below:

  • String It is a required parameter and is used to specify the object to calculate the length of the buffer. The supported types of strings are String, Buffer, TypedArray, DataView and ArrayBuffer.
  • Encoding: It is an optional parameter. If the object is a string, this parameter specifies its encoding scheme. The Default value of encoding scheme is “utf8”.

Return Value: It returns the number of bytes of the specified object. 

Example 1: 

JavaScript




// Node.js program to demonstrate the
// Buffer.bytelength() method
 
// Create a buffer
const buf = Buffer.alloc(20);
 
// Check the length of a buffer object:
const lenobj = Buffer.byteLength(buf);
 
console.log(lenobj);


Output:

20

Example 2: 

JavaScript




// Node.js program to demonstrate the
// Buffer.bytelength() method
 
// Check the length of a buffer object:
const len = Buffer.byteLength('GeeksForGeeks');
 
console.log(len);


Output:

13

Note:

  • In Node.js v7.0.0, an invalid input parameter will throw an error.
  • In Node.js v5.10, the value of the string parameter can be any TypedArray, DataView, or ArrayBuffer.
  • This method is added to node.js v0.1.90.

Reference: https://nodejs.org/docs/latest-v11.x/api/buffer.html#buffer_class_method_buffer_bytelength_string_encoding


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads