NodeJS Buffers

Home / NodeJS Buffers

NodeJS Buffers

December 9, 2015 | Article | No Comments

Natively, JavaScript is not very good at handling binary data. Therefore, NodeJS adds a native buffer implementation and still using JavaScript’s way to manipulate it. The class here is the standard way in Node to transport data.

Generally, buffer can be passed on every Node API which require data to be sent. Also, when receiving data on a callback, we get a buffer (except when we specify stream encoding, in which we get a string).

Create a Buffer

The default encoding format in NodeJS is UTF-8. To create a Buffer from UTF-8 string, we can do:

var buff = new Buffer('Hello World');

A new buffer can also be created from other encoding format. As long as we specify the encoding format in second argument, there is no problem:

var buf = new Buffer('8b76fde713ce', 'base64');

Accepted encodings are: “ascii”, “utf8”, and “base64”.

We can also create a new empty buffer by specify the size:

var buf = new Buffer(1024);

Accessing Buffer

Accessing a buffer is like accessing an array of string. We use [] to access individual ‘character’.

buf[20] = 127;   // Set byte 20 to 127

Format Conversion

A data held on a buffer using an encoding format can be converted to other encoding format.

var str  = buf.toString('utf8');     // UTF-8
var str1 = buf.toString('base64');   // Base64
var str2 = buf.toString('ascii');    // ASCII

When you don’t specify the encoding, Node will assume we are going to use UTF-8. If you need specific encoding, pass it as the argument.

Slice a Buffer

A buffer can be sliced into a smaller buffer by using the appropriately named slice() method.

var buffer = new Buffer('A buffer with UTF-8 encoded string');
var slice = buffer.slice(10,20);

On above code, we slice the original buffer that has 34 bytes into a new buffer that has 10 bytes equal to the 10th to 20th bytes of original buffer.

Note that the slice function does not create new buffer memory, it uses the original untouched buffer underneath.

Copy from Buffer

We can copy a part of a buffer into another pre-allocated buffer by:

var buffer = new Buffer('A buffer with UTF-8 encoded string');
var slice = new Buffer(10);
var targetStart = 0,
    sourceStart = 10,
    sourceEnd = 20;

buffer.copy(slice, targetStart, sourceStart, sourceEnd);

It should be self-explained. Here we copy part of buffer into slice, but only data on positions 10 through 20.

, ,

About Author

about author


A man who is obsessed to low level technology.

Leave a Reply

Your email address will not be published. Required fields are marked *

Social media & sharing icons powered by UltimatelySocial