1

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?

3
  • The function ran nicely for me :/ Commented Jun 7, 2012 at 14:27
  • What version of node.js is this ? Commented Jun 7, 2012 at 14:28
  • I'm not sure if it is advisable to alter the buffer length like this, I'm actually surprised that Node even allows it. Commented Jun 7, 2012 at 14:29

1 Answer 1

5

: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.

Sign up to request clarification or add additional context in comments.

3 Comments

As a result variable „a“ becomes string, nor Buffer. That's nice when you work with strings, but wrong when you work with binary Buffers.
from your example i got confused >_>
Why the if (buffer) in the first forEach? I mean, you're in forEach, of course it's going to exist. Something I'm not seeing? :p

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.