title: Buffer.concat vs Buffer.copy in nodejs
body: <p>I have two cases on using node js <code>Buffer</code> in different place:</p>
  
  <ol>
  <li>Buffer accumulation, which I have several buffers and will combine all of
  them together in the end.</li>
  <li>Buffer writer, which I just need to resize the Buffer when it's
  insufficient anymore to hold more data.</li>
  </ol>
  
  <p>Naturally, I will use <code>Buffer.concat</code> for the first case and <code>Buffer.copy</code> for
  the second case. But, that can be reversed in which I can use <code>Buffer.copy</code> for
  the first case and <code>Buffer.concat</code> for the second case.</p>
  
  <p>Implementation 1 <code>Buffer.concat</code> for first case and <code>Buffer.copy</code> for second case:</p>
  
  <pre><code>// first case: buffer accumulation
  const result = Buffer.concat([arrayOfBuffers])
  
  // second case: buffer writer
  if (oldbuffer.length - offset &lt; newdata.length) {
    const newsize = oldbuffer.length * growthFactor + newdata.length
    const newbuffer = Buffer.alloc(newsize)
    oldbuffer.copy(newbuffer)
    newdata.copy(newbuffer, offset)
    result = newbuffer
  }
  // newbuffer is the end result
  </code></pre>
  
  <p>Implementation 2 <code>Buffer.copy</code> for second case and <code>Buffer.concat</code> for first case:</p>
  
  <pre><code>// first case: buffer accumulation
  const totalSize = arrayOfBuffers.reduce((size, buff) =&gt; size + buff.length, 0)
  const result = Buffer.alloc(totalSize)
  let offset = 0
  for (const buff of arrayOfBuffers) {
    buff.copy(result, offset)
    offset += buff.length
  }
  
  // second case: buffer writer
  const result = Buffer.concat([oldbuffer, newdata])
  </code></pre>
  
  <p>I don't know how both <code>concat</code> and <code>copy</code> internally works in node js. So,
  which method is best for both case?</p>