Software Development

Node.js Buffer Operations

Pure javascript is not efficient in handling binary data. Node.js has native layer implementation for handling binary data, which is buffer implementation with syntaxs of javascript. In node.js we have buufer in all operations for read nad write data.

Some points to be noted for node.js buffer implementation –

  • A> Buffer can not be resized.
  • B> Raw data from transport layer are stored in buffer instances.
  • C> Buffer corresponds to raw memory allocation outside the V8 javascript engine.

Now to make short, we will come to syntax.

To create a buffer for utf-8 encoded string by default:

var buf = new Buffer('Hello Node.js...');

To print the buffer, we can write:

console.log(buf);

But it will show us the memory allocated spaces.

To print the text,as we have entered, we have to write:

console.log(buf.toString());

To create a buffer of pre-allocated size, we need to write as:

var buf = new Buffer(256);

Also we can store valye in each of the pre-allocated array with the following syntax:

buf[10] = 108;

We can put encoding while creating the buffer or while printing it with:

var buf = new Buffer('Hello Node.js...','base64');

or

console.log(buf.toString('base64'));

A buffer can be sliced to small buffers with the following syntax:

var buffer = new Buffer('this is a good place to start');
var slice = buffer.slice(10, 20);

Here the new buffer variable “slice” will be populated with “good place” which starts from 10th byte and ends with 20th byte of the old buffer.

Also to copy from a buffer to another buffer variable we need to write as

var buffer = new Buffer('this is a good place to start');
var slice = new Buffer(10);
var startTarget = 0,start = 10,end = 20;
buffer.copy(slice, startTarget, start, end);

Here the values will be copied from old buffer to new buffer.

There are in-depth documentation of Buffer class can be found here.
 

Reference: Node.js Buffer Operations from our JCG partner Piyas De at the Phlox Blog blog.

Piyas De

Piyas is Sun Microsystems certified Enterprise Architect with 10+ years of professional IT experience in various areas such as Architecture Definition, Define Enterprise Application, Client-server/e-business solutions.Currently he is engaged in providing solutions for digital asset management in media companies.He is also founder and main author of "Technical Blogs(Blog about small technical Know hows)" Hyperlink - http://www.phloxblog.in
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button