Nodejs Buffers

Nodejs gives buffer class to store raw data. It is used extensively when dealing with TCP Streams or file system.

We can create buffers using the below methods.
var buf = new Buffer(10); //using uninitiated buffer of 10 octets
var buf = new Buffer([10, 20, 30, 40, 50]);   // using an aray
var buf = new Buffer("Hello World", "utf-8");   // using a string

Writing to buffers

buf.write(string[, offset][, length][, encoding])
String− This is the data string to buffer to write.
Offset− This is the buffer index for starting writing to. Defaults to 0.
Length− This is the number of writable bytes. Buffer.length defaults to.
Encoding− Usable encoding. Its default encoding is ‘utf8.’

This method returns written octet numbers

Create a file “node-buffer.js” with above code
buf = new Buffer(256);
len = buf.write("Hello world");
console.log("Octets written : "+  len);

Below SS shows the output

node buffer js

Reading from Buffers

buf.toString([encoding][, start][, end])

Above command used to read from the buffer. Eg, when we read a file, file data returned is a buffer and we use the toString method to convert and print it in a readable manner. We will use this in node file service.

Other permitted Buffers methods are
  • toJSON()
  • concat(list[, totalLength])
  • compare(otherBuffer);
  • copy(targetBuffer[, targetStart][, sourceStart][, sourceEnd])
  • slice([start][, end])
  • length
  • isEncoding
  • isBuffer
  • byteLength
Subscribe Now