Buffers in Node.js

Node.js has a Buffer class to handle raw binary data. Instances of Buffer class are fixed-size raw memory allocations outside the V8 heap. The class is global means you don't need to import it using require(). They are way of temporarily storing data while moving it from one place to another.

The size of buffers is specified in bytes when it is created and cannot be changed.

Prior to version 6, to create a 12 byte uninitialized buffer,

var myBuffer1 = new Buffer(12);

Starting from V6, new buffer APIs Buffer.from(), Buffer.alloc() and Buffer.allocUnsafe()

Using these a buffer can be created as

const myBuffer1 = Buffer.alloc(12);

A faster way of creating a buffer is

const myBuffer2 = Buffer.allocUnsafe(12);

But such an instance might contain old data that needs to rewritten with fill() or write(). A buffer initialized with values from an array can be created as

const myBuffer3 = Buffer.from([2, 4, 6, 8, 10, 12]);

To create a buffer from a string with UTF-8 encoding,

const myBuffer4 = Buffer.from('hello', 'utf8');

Availability of buffers makes it easier to work with TCP streams, filesystems etc. Node modules such a http and fs use buffers internally. Buffers are better in performance than strings when dealing with raw binary data. Using buffers allows you to directly work with memory outside of V8 heap.


Post a comment

Name

Your Comment

Email (We dont publish it)

Comments

Nothing yet..be the first to share wisdom.