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.
xxxxxxxxxx
1
const chunks = [];
2
3
chunks.push(Buffer.from([0x00, 0x01])); // chunk 1
4
chunks.push(Buffer.from([0x02, 0x03])); // chunk 2
5
chunks.push(Buffer.from([0x04, 0x05])); // chunk 3
6
7
// put more chunks here ...
8
9
const buffer = Buffer.concat(chunks);
xxxxxxxxxx
1
const GrowingBuffer = () => {
2
const chunks = [];
3
return {
4
append: (chunk) => {
5
chunks.push(chunk);
6
},
7
concat: () => {
8
return Buffer.concat(chunks);
9
}
10
};
11
};
12
13
14
// Usage example:
15
16
const builder = GrowingBuffer();
17
18
builder.append(Buffer.from([0x00, 0x01])); // buffer chunk 1
19
builder.append(Buffer.from([0x02, 0x03])); // buffer chunk 2
20
builder.append(Buffer.from([0x04, 0x05])); // buffer chunk 3
21
22
// put more chunks here ...
23
24
const buffer = builder.concat(); // [0, 1, 2, 3, 4, 5]