Buffers

In the past the JavaScript language had no mechanism for reading or manipulating streams of binary data. The Buffer class was introduced as part of the Node.JS language API, because JavaScript does not handle straight binary data very well.

Since Node.JS is a server technology and has to deal with streams (TCP/UDP) and reading and writing to files and network.

So the buffer was the solution to the old way of working with encoded strings.

The buffer in Node.JS is a way of handling raw binary data. It is done with Raw memory allocation outside the V8 heap inside the Global namespace object. The buffer object is global.

An example of how to allocate simple buffer:

var buff = new Buffer('some arbitrary string');

The buffer can be created with different string encodings: 'ascii', 'utf8', 'ucs2', 'base64', 'binary', 'hex'. (later on explanation on each one of these).

You can also init buffer from an array:

var buffer = new Buffer([2,3,4]);

Once allocated the buffer cannot be resized.

A buffer can be initialized to certain size like:

var buffer = new Buffer(4096);

A buffer can be sliced to smaller buffer as follows:

var buffer = new Buffer("this is my first buffer");

var partSliced = buffer.slice(12,5);

results matching ""

    No results matching ""