What is the Buffer.byteLength function in Node.js?

Share

The Buffer.byteLength function is used to calculate the size of a pre-declared object of the following kinds of data-structures in bytes:

  • String
  • Buffer
  • TypedArray
  • DataView
  • ArrayBuffer
  • SharedArrayBuffer

Syntax

To use Buffer.byteLength, the following syntax is used:

Buffer.byteLength(string, encoding)

Parameters

The Buffer.byteLength function takes in two arguments:

  • string - the name of the object to calculate the size of (in bytes)
  • encoding - encoding in which values inside the data-structure are formatted

encoding is an optional parameter

The following illustration lists some of the most commonly used encodings supported by the Buffer.byteLength function.

%0 node_1625729641242 utf8 node_1 base64 node_1625729643445 base64url node_1625729671146 hex node_1625729714744 ucs2
Supported Encodings.

For an object of type string, the encoding is assumed to be UTF-8 by default.

Return value

It returns the size of the data-structure in bytes.

Example

The following program allocates to buffers that contain the same string.

However, the string in one of the buffers is encoding in UTF-8 and UCS-2 in the other. UCS-2 is a subset of the UTF-16 encoding format supported by Node.js.

In UCS-2 each character is 2 bytes long, and in UTF-8 each character is 1 byte long.

Using the Buffer.byteLength function, we calculate the size of the two buffers in bytes. As expected, the size of the second buffer, encoded in UCS-2, is double the size of the first buffer and greater than the number of data elements in it, i.e., 9.

var buffer_utf8 = Buffer.from("Educative",);
console.log(buffer_utf8.toString())
console.log("Size for the string above encoded in UTF-8:", Buffer.byteLength(buffer_utf8), "bytes")
var buffer_utf16 = Buffer.from("Educative", "ucs2");
console.log("Size for the same string encoded in UCS-2, which is the subset of UTF-16 supported by Node:",Buffer.byteLength(buffer_utf16), "bytes")
Copyright ©2024 Educative, Inc. All rights reserved