What are node.js buffers?

Photo by Max Chen on Unsplash

What are node.js buffers?

A buffer is a piece of memory that stores binary data. It is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. Buffers are used to represent a sequence of binary data in Node.js and are often used when interacting with data that is stored in a binary format, such as a file on the filesystem or an HTTP response from a server.

Buffers can be created in several ways in Node.js:

const buf1 = Buffer.alloc(10);  // creates a buffer of 10 bytes
const buf2 = Buffer.from([1, 2, 3]);  // creates a buffer from an array of bytes
const buf3 = Buffer.from('hello world');  // creates a buffer from a string

Once a buffer has been created, you can read from or write to it using the array-like syntax provided by Node.js.

const buf = Buffer.alloc(10);

// write to the buffer
buf[0] = 0x61;
buf[1] = 0x62;
buf[2] = 0x63;

// read from the buffer
console.log(buf[0]);  // prints 97 (0x61)
console.log(buf[1]);  // prints 98 (0x62)
console.log(buf[2]);  // prints 99 (0x63)

You can also use the buf.slice() method to create a new buffer that references the same memory as the original buffer, but with a different offset and length. This can be useful for processing large buffers in chunks.

const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);

const sub1 = buf.slice(0, 5);  // sub1 contains [1, 2, 3, 4, 5]
const sub2 = buf.slice(5);     // sub2 contains [6, 7, 8, 9, 10]