Rahul Shivsharan Rahul Shivsharan - 1 month ago 7
Node.js Question

Why Buffer copy prints me some garbage value?

I am new to node.js,

I was reading on Node.js Buffers.

I stumbled on buffer.copy method.

Wrote a code which is as follows,

var bufferOne = new Buffer("This is China");
var bufferTwo = new Buffer(20),
startTarget = 0,
sourceStart = 8,
sourceEnd = 0;
var bufferLength = bufferOne.length;
sourceEnd = bufferLength;
console.log("Buffer length "+bufferLength);
bufferOne.copy(bufferTwo,startTarget,sourceStart,sourceEnd);

console.log("Buffer1 "+bufferOne.toString());
console.log("Buffer2 "+bufferTwo.toString());


The output is as follows,

Buffer length 13
Buffer1 This is China
Buffer2 China


But sometimes it also prints garbage output after "China", as follows,

Buffer length 13
Buffer1 This is China
Buffer2 China���*�


Sometimes,

Buffer length 13
Buffer1 This is China
Buffer2 China���


Can somebody please tell me whats going on ?

Answer

The length of bufferTwo is 20, but you're only copying 13 bytes. The remaining 7 bytes contain semi-random data.

Documented here:

Passing a number as the first argument to Buffer() (e.g. new Buffer(10)), allocates a new Buffer object of the specified size. The memory allocated for such Buffer instances is not initialized and can contain sensitive data.