EN
Node.js - append data to Buffer
7
points
In this short article, we would like to show how to append data to buffer in Node.js.
Quick solution:
The best way is to collect chunks in array and concat them togather.
const chunks = [];
chunks.push(Buffer.from([0x00, 0x01])); // chunk 1
chunks.push(Buffer.from([0x02, 0x03])); // chunk 2
chunks.push(Buffer.from([0x04, 0x05])); // chunk 3
// put more chunks here ...
const buffer = Buffer.concat(chunks);
Reusable logic
const GrowingBuffer = () => {
const chunks = [];
return {
append: (chunk) => {
chunks.push(chunk);
},
concat: () => {
return Buffer.concat(chunks);
}
};
};
// Usage example:
const builder = GrowingBuffer();
builder.append(Buffer.from([0x00, 0x01])); // buffer chunk 1
builder.append(Buffer.from([0x02, 0x03])); // buffer chunk 2
builder.append(Buffer.from([0x04, 0x05])); // buffer chunk 3
// put more chunks here ...
const buffer = builder.concat(); // [0, 1, 2, 3, 4, 5]