The Buffer.byteLength
function is used to calculate the size of a pre-declared object of the following kinds of data-structures in bytes:
To use Buffer.byteLength
, the following syntax is used:
Buffer.byteLength(string, encoding)
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.
For an object of type
string
, the encoding is assumed to beUTF-8
by default.
It returns the size of the data-structure in bytes.
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 inUTF-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")
Free Resources