Node.JS Buffers

We have covered most of the basic concepts of Node.js in previous articles. In this article we shall discuss a bit more advanced topic i.e. node.js buffers. Node.js applications are written in JavaScript. JavaScript is very powerful when it comes to dealing with unicode data. However, we run node.js application outside the browser. Therefore, we often need to interact with octet stream and store them on the memory heap in the form of binary data. Node.js contains a global buffer class that is used to read and write octet streams

Initializing Node.js Buffers

There are three ways to initialize buffers in Node.js.

  • var bf = new Buffer(20) : This creates a buffer of 20 Octets
  • var buf = new Buffer([7,14,21,28,35]): This creates a buffer from array
  • var buf = new Buffer(“Knowledge Hills”, “utf-8”) : This creates a buffer from string along with encoding type.

Reading and writing 9 Digits to and from buffer

In the following example we shall create a buffer that stores octet values for digits 1 to 9. We shall then read this buffer via different encoding techniques. Take a look at the following example.

var bf = new Buffer(9);
for (var i = 0 ; i < 9 ; i++) {
  bf[i] = i + 49;

console.log( bf.toString('ascii'));       // outputs: 1234567489
console.log( bf.toString('ascii',0,6));   // outputs: 123456
console.log( bf.toString('utf8',0,6));    // outputs: 123456
console.log( bf.toString(undefined,0,3)); // default utf-8 encoding will be used 123

Download the code Try the code

In the above code we initialize a buffer with 9 octets. At each octet we specified the ASCII value for numeric integers 1 to 9. Next when we read the buffer we use buffer.toString() method. This method takes three parameters, first one is the encoding type, 2nd is the starting index to read and the third is ending index. Similarly if you are directly writing the buffer using a string you can use buffer.write method. It takes four parameters: string, offset, length and encoding.

Buffer to JSON Conversion

You can easily convert buffer data to JSON format via buffer.toJSON() function. Take a look at the following example.

var bf = new Buffer('Knowledge hills: learning website');
var jsn = bf.toJSON(bf);


Download the code Try the code

The above piece of code will convert string passed to buffer into its JSON representation and will print it on screen.

<<< Node.JS Event EmitterNode.JS Buffer II >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .