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.
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:
But it will show us the memory allocated spaces.
To print the text,as we have entered, we have to write:
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 = 108;
We can put encoding while creating the buffer or while printing it with:
var buf = new Buffer('Hello Node.js...','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.