Nodejs Buffers

Job-ready Online Courses: Click for Success - Start Now!

Today we will be discussing Nodejs buffers and their properties in detail with code and examples.

Nodejs Buffers:

It is an area of memory present outside the v8 javascript engine. It is of fixed size. This is like an array where each item is in bytes.

Why use a buffer in Nodejs?

Normally we deal with string data types but in order to deal with binary data types efficiently we have to use buffer.

Creating Buffers in Nodejs:

In order to store something on buffer we have to first create a buffer. Below are different ways for creating Buffer:

1. Creating a buffer of size 10 octets which is not initialised

Syntax:

var buf = Buffer.alloc(10);

2. Creating buffer for the given array

Syntax:

var buf = Buffer.from([10, 20, 30, 40, 50]);

3. Creating buffer for the given string with encoding:

Syntax:

var buf = Buffer.from("DataFlair", "utf-8");

Writing to Buffers in Nodejs:

Now we will look at how to store our data in a buffer. Below syntax shows how we can write to a buffer.

Syntax:

buf.write(string[, offset][, length][, encoding])

Parameter:

  • string : It represents the data that has to be written in the buffer.
  • Offset: This represents the index from where the writing will start.
  • Length: It represents the number of bytes.
  • Encoding: It represents the type of encoding, by default it is “UTF8”

Return value:

It returns the number of octets written. Example of writing to buffer:

buf = new Buffer(256);
len = buf.write("DataFlair");
console.log(len)

Output:

9

Reading from Nodejs Buffers:

In order to read the data store in our buffer we will be using the below syntax:

Syntax:

buf.read([encoding],[, start],[, end])

Parameter:

  • Encoding: It represents the type of encoding, by default it is “UTF8”
  • Start: It indicates the index from which reading will start.
  • End: It represents the index till which it has to read.

Return value:

It returns the string from the buffer.

Example of reading from a buffer:

var buffer = Buffer.alloc(16)
buffer.write("DataFlair", "utf-8")
console.log(buffer.toString("utf-8", 0, 9))

Output:

nodejs buffer write

Buffer to Json:

To convert the buffer data to a json format buffer.toJSON() method is used.

Syntax:

buffer.toJSON()

Return type:

It returns a json value for the given buffer.

Code for converting buffer to json:

let buffer = new Buffer('Welcome to DataFlair');
let json = buffer.toJSON(buffer);
console.log(json);

Output:

nodejs buffer to json

Concatenate Buffer:

It is used to concatenate two buffers together to make a single buffer. Below is syntax for doing the same.

Syntax:

Buffer.concat(list[, totalLength])

Parameter:

  • List: It is the list of buffers that will be concatenated
    totalLength: Represents the total length after concatenation
  • Return value:
    Returns the concatenated buffer.

Example of concatenating buffers:

var buffer1 = new Buffer('Data');
var buffer2 = new Buffer('Flair');
var buffer3 = Buffer.concat([buffer1, buffer2]);

console.log(buffer3.toString());

Output:

nodejs buffer concat

Iterating over a buffer:

In order to iterate a buffer use a for loop which you use in javascript.

Code for iterating over a buffer

const buf = Buffer.from('DataFlair!')
for (const item of buf) {
    console.log(item)
}

Output:

nodejs buffer iterate

Length of Buffer:

To get the length of the buffer that you have created use the buffer.length() method. It will return a number representing the length of the buffer.

Code to know the length of buffer

const buf = Buffer.from('DataFlair')
console.log(buf.length)

Output:

nodejs buffer length

Changing contents of Nodejs buffers:

When we want to edit our buffer we treat it like an array and replace the content in the same way as we do incase of arrays.

Code for changing the contents of buffer

const buf = Buffer.from('DataFlair')
buf[0] = 100
console.log(buf.toString())

Output

nodejs buffer replace

Slicing buffer in Nodejs:

Slicing is used when we want to get a particular part from our buffer.

Code for Slicing the buffer:

const buf = Buffer.from('DataFlair')
const slice = buf.subarray(0, 4)
console.log(slice.toString())

Output:

nodejs buffer slice

Copy Nodejs buffer:

To copy data from one buffer to another we make another buffer of the same size and then set the content of the buffer.

Code for Copying a buffer:

const buf = Buffer.from('DataFlair')
let bufcopy = Buffer.alloc(9)
bufcopy.set(buf)
console.log(bufcopy.toString())

Output:

nodejs copy buffer

Compare Nodejs buffers:

To compare one buffer with another we use the buffer.compare method.

Syntax:

buffer.compare(‘anotherBufferName’)

Code for Comparing Nodejs buffers:

let buffer1 = new Buffer('Hello from DataFlair');
let buffer2 = new Buffer('Welcome to DataFlair');
let result = buffer1.compare(buffer2);
if (result < 0) {
    console.log(buffer1 + " comes before " + buffer2);
} else if (result === 0) {
    console.log(buffer1 + " is same as " + buffer2);
} else {
    console.log(buffer1 + " comes after " + buffer2);
}

Output:

Hello from DataFlair comes before Welcome to DataFlair.

Methods Reference:

  • Comparing buffer:

To compare two buffers we use the buffer.compare(buf1,buf2)

  • isBuffer:

To know whether the given object is a buffer or not we use the buffer.isBuffer(obj) method.

  • isEncoding:

It returns true if the encoding provided is a valid encoding.

Summary

In this article, we discussed Nodejs buffers and their different properties. Hope you liked the article.

Did you like our efforts? If Yes, please give DataFlair 5 Stars on Google

courses

DataFlair Team

DataFlair Team is a group of passionate educators and industry experts dedicated to providing high-quality online learning resources on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. With years of experience in the field, the team aims to simplify complex topics and help learners advance their careers. At DataFlair, we believe in empowering students and professionals with the knowledge and skills needed to thrive in today’s fast-paced tech industry. Follow us for Free courses, expert insights, tutorials, and practical tips to boost your learning journey.

Leave a Reply

Your email address will not be published. Required fields are marked *