Looking at the implementation of Buffer.concat: It seems to be doing exactly what you suggested as replacement in implementation 2/first case: Create a new buffer with the calculated total length, then copy all buffers into the output.

So, based on that it seems reasonable to continue to use Buffer.concat directly, because the code is more concise, easier to follow, and describes better what you want to do ("concatenate all these buffers!")

For the writer case: Your suggested implementations aren't equivalent -- the first one would leave space at the end for adding new data, while the second implementation provides exactly the space needed for the existing buffers. If you need the extra space (optimization for expected future writes, for example), then stick to the first variant, otherwise the same argument applies: Using concat is more concise and easier to read.

Answer from ankon on Stack Overflow
🌐
W3Schools
w3schools.com › nodejs › met_buffer_concat.asp
Node.js Buffer.concat() Method
let buf1 = Buffer.from('a'); let buf2 = Buffer.from('b'); let buf3 = Buffer.from('c'); let arr = [buf1, buf2, buf3]; let buf = Buffer.concat(arr); console.log(buf); Run example »
🌐
Node.js
nodejs.org › api › buffer.html
Buffer | Node.js v26.11.1 Documentation
import { Buffer } from 'node:buffer'; // Create a single `Buffer` from a list of three `Buffer` instances. const buf1 = Buffer.alloc(10); const buf2 = Buffer.alloc(14); const buf3 = Buffer.alloc(18); const totalLength = buf1.length + buf2.length + buf3.length; console.log(totalLength); // Prints: 42 const bufA = Buffer.concat([buf1, buf2, buf3], totalLength); console.log(bufA); // Prints: <Buffer 00 00 00 00 ...> console.log(bufA.length); // Prints: 42 const { Buffer } = require('node:buffer'); // Create a single `Buffer` from a list of three `Buffer` instances.
Discussions

node.js - Buffer.concat vs Buffer.copy in nodejs - Stack Overflow
I have two cases on using node js Buffer in different place: Buffer accumulation, which I have several buffers and will combine all of them together in the end. Buffer writer, which I just need to ... More on stackoverflow.com
🌐 stackoverflow.com
node.js Buffers concat is driving me nuts
You probably need special software to rewrite the wav header: http://www.topherlee.com/software/pcm-tut-wavformat.html More on reddit.com
🌐 r/node
14
4
June 18, 2018
How to concat buffers with delimiter in node.js?
I'm trying to concat two buffers with a space in between them in Node.js. More on stackoverflow.com
🌐 stackoverflow.com
Buffer.concatenate only produces buffer of last buffer in the array
I am trying to concatenate an array of buffers using the Buffer.concat() function. From the documentation it appears that the first input is an array of buffers, and the second input is the buffer total length. I then convert that to a string and pass it to another function to be emailed to ... More on github.com
🌐 github.com
7
June 21, 2019
🌐
Educative
educative.io › answers › how-to-use-the-bufferconcat-function-in-nodejs
How to use the Buffer.concat() function in Node.js
The Buffer.concat() function combines multiple instances of buffers into a single buffer and returns it.
🌐
TutorialsPoint
tutorialspoint.com › nodejs › nodejs_buffer_concat_method.htm
Node.js - Buffer.concat() Method
The NodeJS Buffer.concat() method will return a single buffer object by concatenating all the given buffer objects. If the buffers used have no items or the length of the buffers is 0, the final buffer created will be a new zero-length buffer.
🌐
GeeksforGeeks
geeksforgeeks.org › node.js › node-js-buffer-concat-method
Node.js Buffer.concat() Method - GeeksforGeeks
April 11, 2023 - // Returns a new buffer with the // copy of the passed string const buf1 = Buffer.from("Good"); // Returns another buffer with // copy of the passed string const buf2 = Buffer.from("morning"); const buf3 = Buffer.from("everyone"); // Creates an array of buffers const list = [buf1, buf2, buf3]; // Concatenates all buffer objects // into one buffer const newbuff = Buffer.concat(list); console.log("The concatenated buffer:"); // Displays the concatenated buffer console.log(newbuff); ... Note: The above program will compile and run by using the node index.js command. Reference: https://nodejs.org/dist/latest-v13.x/docs/api/buffer.html#buffer_class_method_buffer_concat_list_totallength
🌐
npm
npmjs.com › package › buffer-concat
buffer-concat - npm
August 2, 2016 - var b3 = bufferConcat([b1, b2]); console.log(b3.toString()); // for datas concat · var http = require('http'); var options = { host: 'nodejs.org' }; http.get(options, function (res) { var chunks = []; var size = 0; res.on('data', function (chunk) { size += chunk.length; chunks.push(chunk); }); res.on('end', function () { var data = bufferConcat(chunks, size); console.log(data.toString()); }); }); Node.js 0.8.0 and newer provides this functionality out of the box on the native buffer object (Buffer.concat).
      » npm install buffer-concat
    
Published: Aug 02, 2016
Version: 1.0.0
🌐
GitHub
github.com › node-modules › buffer-concat
GitHub - alibaba-archive/buffer-concat: concat patch for Buffer in node < 0.8. · GitHub
February 8, 2023 - // require before you use Buffer.concat var bufferConcat = require('buffer-concat'); var b1 = new Buffer('Hello'); var b2 = new Buffer(' world'); var b3 = bufferConcat([b1, b2]); console.log(b3.toString()); // for datas concat var http = require('http'); var options = { host: 'nodejs.org' }; http.get(options, function (res) { var chunks = []; var size = 0; res.on('data', function (chunk) { size += chunk.length; chunks.push(chunk); }); res.on('end', function () { var data = bufferConcat(chunks, size); console.log(data.toString()); }); }); Node.js 0.8.0 and newer provides this functionality out of the box on the native buffer object (Buffer.concat).
Author: alibaba-archive
Find elsewhere
🌐
Melvin George
melvingeorge.me › blog › combine-buffers-nodejs
How to combine Buffers in Node.js? | MELVIN GEORGE
September 26, 2020 - To combine Buffer instances in Node.js, we can use the concat() method in the Buffer class.
🌐
LogRocket
blog.logrocket.com › home › node.js buffer: a complete guide
Node.js buffer: A complete guide - LogRocket Blog
June 4, 2024 - var buffer1 = Buffer.from('x'); var buffer2 = Buffer.from('y'); var buffer3 = Buffer.from('z'); var arr = [buffer1, buffer2, buffer3]; /*This will print buffer, !concat [ <Buffer 78>, <Buffer 79>, <Buffer 7a> ]*/ console.log(arr); //concatenate buffer with Buffer.concat method var buf = Buffer.concat(arr); //This will print <Buffer 78 79 7a> concat successful console.log(buf);
🌐
Reddit
reddit.com › r/node › node.js buffers concat is driving me nuts
r/node on Reddit: node.js Buffers concat is driving me nuts
June 18, 2018 -

Hello reddit,

i am currently investigating in a bug that is driving me crazy the whole day. Googling, Stackoverflow, every blog says that the Buffer.concat(list, length) function is there to achieve the appending of all buffers to a single one. But all i get after concatenating multiple buffers is the first one.

I am fetching small .wav files from a server and try to append them to a single new buffer and send it over to the frontend. Those files are small 2 seconds samples.

On the frontend i want to turn that buffer into an AudioBuffer. Which works, but only plays the first buffer of the buffer list.

I use node-fetch for that on the express.js backend

fetch(url).then(response => response.buffer());

I do that for a number of 1-20 files and store those buffers in an array.

I checked every buffer in that array and wrote it to a file on the server. Every single file is playable and unique.

But if i do that

let concatedBuffers = Buffer.concat(allBuffers, totalLength);

and write that big buffer ( got the size of all buffers combined, still below 5 MB) to a file, it only represents the first buffer item.

I tried to use a library for buffer concat, i even wrote an implementation. But still the same result. Only the first buffer is there after appending.
Does someone have a clue and can point out my misleading understanding of Buffers, please?

The implementation ( copied from buffer-concat library):
function concatenateBuffers( list, length? ){
let size = 0;
if (!Array.isArray(list)){
throw new Error('Usage: concatenateBuffers(list, [length])');
}

if (list.length === 0){
return new Buffer(0);
} else if (list.length === 1){
return list[0];
}

if (typeof length !== 'number'){
size = 0;
for (let i = 0; i < list.length; i++){
let buf = list[i];
size += buf.length;
}

console.log('calculated Size: ', size);
} else {
size = length;
}

let buffer = new Buffer(size);
let pos = 0;
for (let i = 0; i < list.length; i++){
let buf = list[i];
buf.copy(buffer, pos);
pos += buf.length;
}
return buffer;
}

🌐
W3Schools
w3schools.am › nodejs › met_buffer_concat.html
Node.js Buffer.concat() Method
The concat() method joins all buffer objects in an array into one buffer object.
🌐
Java2s
java2s.com › ref › javascript › nodejs-buffer-concatenate.html
Node.js Buffer Concatenate
// example//w w w .java 2 s . c o m var buffer1 = Buffer.from('test'); var buffer2 = Buffer.from('Simply Easy Learning'); var buffer3 = Buffer.concat([buffer1,buffer2]); console.log("buffer3 content: " + buffer3.toString()); PreviousNext
🌐
GitHub
github.com › nodejs › help › issues › 1994
Buffer.concatenate only produces buffer of last buffer ...
June 21, 2019 - let buffLength = 0; for (let i = 0; i <= arrBuffers.length - 1; i++) { buffLength = buffLength + arrBuffers[i].length; } const buffer = Buffer.concat(arrBuffers, buffLength); const attachments = [{ content: buffer.toString('base64'), filename: `invoice-${invoiceDate}.pdf`, type: 'application/pdf', disposition: 'attachment', content_id: customer.id }]; return resolve(attachments);
Author: nodejs
🌐
Medium
medium.com › @mvsg › buffers-in-node-js-what-they-are-and-why-they-matter-610b34b98915
Buffers in Node.js: What They Are and Why They Matter | by Marcos Vinicius Gouvea | Medium
February 8, 2023 - const firstBuffer = Buffer.from('Hello, '); const secondBuffer = Buffer.from('world!'); const combinedBuffer = Buffer.concat([firstBuffer, secondBuffer]); console.log(combinedBuffer.toString()); // Output: "Hello, world!" As you can see, Buffers provide a flexible and efficient way to store and manipulate binary data in Node.js. Whether you’re working with images, audio, video, or raw data, you’ll find that Buffers are a powerful tool that can help you build high-performance and scalable applications. Nodejs ·
🌐
Node.js
nodejs.org › download › release › v10.2.0 › docs › api › buffer.html
Buffer | Node.js v10.2.0 Documentation
// Create a single `Buffer` from a list of three `Buffer` instances. const buf1 = Buffer.alloc(10); const buf2 = Buffer.alloc(14); const buf3 = Buffer.alloc(18); const totalLength = buf1.length + buf2.length + buf3.length; console.log(totalLength); // Prints: 42 const bufA = Buffer.concat([buf1, buf2, buf3], totalLength); console.log(bufA); // Prints: <Buffer 00 00 00 00 ...> console.log(bufA.length); // Prints: 42
🌐
DEV Community
dev.to › sfundomhlungu › buffers-in-nodejs-what-they-do-why-you-should-care-46p1
Buffers in Node.js: What They Do & Why You Should Care - DEV Community
July 22, 2025 - import { Buffer } from 'node:buffer'; import { writeFileSync } from 'node:fs'; async function serialize(data) { const b = Buffer.from(data.data, "utf-8"); // actual body const contentType = Buffer.from(data.contentType, 'utf-8'); // HTTP header const bodyLength = Buffer.alloc(4); // holds body length bodyLength.writeInt32BE(b.length, 0); // write as 32-bit integer const combinedBuff = Buffer.concat([bodyLength, b, contentType]); console.log(combinedBuff); // full serialized buffer writeFileSync("./binaryData.bin", combinedBuff); // save to file } Many low-level systems rely on this simple process.
Top answer
1 of 2
8

Rather than concatenating every time (which creates a new buffer each time), just keep an array of all of your buffers and concat at the end.

Buffer.concat() can take a whole list of buffers. Then it's done in one operation. https://nodejs.org/api/buffer.html#buffer_class_method_buffer_concat_list_totallength

2 of 2
2

If you read from a file and know the size of that file, then you can pre-allocate the final buffer. Then each time you get a chunk of data, you can simply write it to that large 16Mb buffer.

// use the "unsafe" version to avoid clearing 16Mb for nothing
let buf = Buffer.allocUnsafe(file_size)

let pos = 0
file.on('data', (chunk) => {
    buf.fill(chunk, pos, pos + chunk.length)
    pos += chunk.length
})

if(pos != file_size) throw new Error('Ooops! something went wrong.')

The main difference with @Brad's code sample is that you're going to use 16Mb + size of one chunk (roughly) instead of 32Mb + size of one chunk.

Also, each chunk has a header, various pointers, etc. so you are not unlikely to use 33Mb or even 34Mb... that's a lot more RAM. The amount of RAM copied is otherwise the same. That being said, it could be that Node starts reading the next chunk while you copy so it could make it transparent. When done in one large chunk in the 'end' event, you're going to have to wait for the contact() to complete while doing nothing else in parallel.


In case you are receiving an HTTP POST and are reading it. Remember that you get a Content-Length parameter so you also have the length in that case and can pre-allocate the entire buffer before reading the data.

🌐
DEV Community
dev.to › m__mdy__m › buffers-in-nodejs-1fh2
Buffers in Node.js - DEV Community
December 14, 2023 - Repeats steps 3 and 4 in a loop, reading 1000 bytes at a time and concatenating to the fullFileData Buffer until there is no more data to read.