Kikit Kikit - 7 months ago 27
Node.js Question

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.

Here is my code.

var buff1 = new Buffer("Jumping");
var buff2 = new Buffer("Japang");
var buffSpace = new Buffer(1);
buffSpace[0] = "32";
var newBuff = Buffer.concat([buff1, buffSpace, buff2], (buff1.length + buff2.length + buffSpace.length));

As per official doc, the first argument will be the Array list of Buffer objects. Hence I've created buffSpace for space.

Class Method: Buffer.concat(list[, totalLength])

list : Array List of Buffer objects to concat

totalLength: Number Total length of the buffers when concatenated

I'm getting the result as expected but not sure whether it is right way to do so. Please suggest if any better solution to achieve the same.


There are three changes I would suggest.

First, use Buffer.from() instead of new Buffer(), as the latter is deprecated.

Second, you don't need to pass an argument for totalLength to Buffer.concat(), since it will be calculated automatically from the length of all of the buffers passed. While the docs note it will be faster to pass a total length, this will really only be true if you pass a constant value. What you are doing above is computing the length and then passing that, which is what the concat() function will do internally anyway.

Finally, I would recommend putting this in a function that works like Array.prototype.join(), but for buffers.

function joinBuffers(buffers, delimiter = ' ') {
  let d = Buffer.from(delimiter);

  return buffers.reduce((prev, b) => Buffer.concat([prev, d, b]));

And you can use it like this:

let buf1 = Buffer.from('Foo');
let buf2 = Buffer.from('Bar');
let buf3 = Buffer.from('Baz');

let joined = joinBuffers([buf1, buf2, buf3]);

console.log(joined.toString()); // Foo Bar Baz

Or set a custom delimiter like this:

let joined2 = joinBuffers([buf1, buf2, buf3], ' and ');

console.log(joined2.toString()); // Foo and Bar and Baz