Languages
[Edit]
EN

Node.js - append data to Buffer

7 points
Created by:
Giles-Whittaker
739

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]

 

Alternative titles

  1. Node.js - grow Buffer
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join