Node.JS Buffer II

In the previous article we started a discussion on buffers. We saw different ways of creating buffers in Node.js. We also saw how to write data to a node.js buffer and how to read data from node.js buffer. We also saw how we can convert node.js buffer to JSON. In this article we will study some more buffer functionalities. We shall see how to concatenate two buffers, how to compare two buffers, how to copy two buffers and how to slice buffers. So, let’s get started with the first one.

Buffer Concatenation

Buffer concatenation refers to joining data stored inside two or more than two buffers. To concat buffers, Buffer.concat(arraylist[], total_length ) is used. Here first parameter is the arraylist of all the buffer to concatenate while second argument is the length of each buffer. Take a look at the following example to see buffer concatenation in action.

var buf1 = new Buffer('Knowledge Hills ');
var buf2 = new Buffer('Learn Programming Tutorials');
var buf3 = Buffer.concat([buf1,buf2]);
console.log("Concatenated Buffer: " + buf3.toString());

Download the code Try the code

Buffer Comparison

Buffer comparison compares whether the buffer being compared comes before the first buffer in sort order, or it is same as the first buffer or it comes after the first buffer in the sort order. Buffer.compare(buffer2) method is used for buffer comparison. It returns a number less than zero if the first buffer comes before the second buffer. In case if the two buffers are same, this method returns 0. And finally if first buffer comes after the second buffer, compare method returns a number greater than 0. Take a look at the following example.

var buf1 = new Buffer('Knowledge');
var buf2 = new Buffer('Hills');
var compres = buf1.compare(buf2);

if(compres < 0) {
   console.log(buf1 +" comes earlier than" + buf2);
}else if(compres == 0){
   console.log(buf1 +" is similar to" + buf2);
}else {
   console.log(buf1 +" comes after " + buf2);
}

Download the code Try the code

Buffer Copy

To copy to buffers, buffer.copy(buffer2) method is used. This method copies, contents of the first buffer into buffer2. Take a look at the following example.s

var buf1 = new Buffer('Knowledge');


var buf2 = new Buffer(9);
buf1.copy(buf2);
console.log("Contents of Copied Buffer: " + buf2.toString());

Download the code Try the code

Buffer Slicing

You can also slice contents of a buffer. This is similar to substring method. To slice a buffer, the method buffer.slice(start, end) method is used. Here start specifies index where slicing begins. Similarly, end specifies index where slicing ends. Take a look at the following example.

var buf1 = new Buffer('Knowledgehills');

var buf2 = buf1.slice(9,14);
console.log("Contents of sliced buffer: " + buf2.toString());

Download the code Try the code

<<< Node.JS BuffersNode.JS Streams >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .