I'm trying to create method to append buffers.
Here's code, which takes very strange result:
var offset = 0
var a = new Buffer(0)
var b = new Buffer('test')
offset = a.length
a.length += b.length
a.copy(b, offset)
console.log(a.toString())
// everything works normaly
// returns: test
b = new Buffer('hello')
offset = a.length
a.length += b.length
a.copy(b, offset)
console.log(a.toString())
// code the same
// but returns: test<Buff
// nor: testhello
// at the third time code doesn't works and raise error: targetStart out of bounds
What do I do wrong?
:EDIT:
Got confused by the question. I thought he is going to handle buffers of same type.
Buffers cant be resized as they are defined by a fixed size in Node.js so the best option is to use a function like this
function concat(buffers) {
if (!Array.isArray(buffers)) {
buffers = Array.prototype.slice.call(arguments);
}
var buffersToConcat = [], length = 0;
buffers.forEach(function (buffer) {
if (!Buffer.isBuffer(buffer)) {
buffer = new Buffer(buffer);
}
length += buffer.length;
buffersToConcat.push(buffer);
});
var concatinatedBuffer = new Buffer(length), index = 0;
buffersToConcat.forEach(function (buffer) {
buffer.copy(concatinatedBuffer, index, 0, buffer.length);
index += buffer.length;
});
return concatinatedBuffer;
}
What were you doing wrong? You were trying to manipulate the length of a fixed size allocation in memory by the += method. Hence it threw exception beacause += operator obviously didnt re-allocated memory
*What are we doing here *
Pretty simple we are just making a new buffer out of the argument buffers.