• Node.js Video Tutorials

Node.js - Buffer.byteLength() Method



The NodeJS Buffer.byteLength() method is used to calculate the length in bytes for the buffer object.

Syntax

Following is the syntax of the Node.JS Buffer.byteLength() Method

Buffer.byteLength( string, encoding )

Parameters

This method accepts two parameters. The same is explained below.

  • string −(required) An object of which the length will be calculated. Supported types are: String,Buffer,TypedArray,DataView,ArrayBuffer

  • encoding −:(optional).If the object given is string the encoding has to be specified.By default the encoding used is 'utf-8'.

Return value

The method Buffer.byteLength() will return the length in bytes for the buffer object.

Example

The example will create a buffer using NodeJS Buffer.from() method and find the length using Buffer.byteLength().

const buf = Buffer.from('Hello World');
console.log("The length is :"+Buffer.byteLength(buf));

Output

The length is :11

Example

The example will create a buffer using Buffer.alloc() method and find the length using Buffer.byteLength().

const buf = Buffer.alloc(15);
console.log("The length is :"+Buffer.byteLength(buf));

Output

The length is :15

Example

The example will create a buffer using Buffer.allocUnsafe() method and find the length using Buffer.byteLength().

const buf = Buffer.allocUnsafe(15);
console.log("The length is :"+Buffer.byteLength(buf));

Output

The length is :15

Example

You can directly use the string object inside Buffer.byteLenght() as shown below.

console.log("The length is :"+Buffer.byteLength('Hello World'));

Output

The length is :11
nodejs_buffer_module.htm
Advertisements