Node.js | Buffer.byteLength() Method

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 accept two parameters as mentioned above and described below:

  • String It is a required parameter and 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 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:



filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

20

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

13

Note:

  • In Node.js v7.0.0, invalid input parameter will throw an error.
  • In Node.js v5.10, the value of 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

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.