Node.js Buffers

Node.js Buffers – Node.js Buffer is a class that helps to handle and work with octet streams. Octet streams would generally come into picture when dealing with TCP data streams and file system operations.

Raw memory allocated to buffers is outside the Node.js V8 heap memory.

In this tutorial, we shall learn how to

Node.js – Create Buffer

There are quite multiple ways to create buffer in Node.js. We shall go through each of them one by one.

Buffer of specified length

To create a buffer of specified length, use Buffer.allocUnsafe(int) method.

Syntax

Buffer.allocUnsafe(bufferLength);

bufferLength is an integer specifying the length of buffer to be created.

The buffer created is not initialized, which means it can contain garbage values. You may overwrite the garbage values using fill() or write() methods.

Zero filled buffer of specified length

To create a Zero filled buffer of specified length, use Buffer.alloc(int) method.

Syntax

Buffer.alloc(bufferLength);

bufferLength is an integer specifying the length of buffer to be created. The buffer contains all memory locations filled with zeroes.

Buffer.alloc() is slower than Buffer.allocUnsafe().

Buffer of specified length, filled with a specified value

To create a buffer of specified length and filled with a specified value, use Buffer.alloc(int, int) method.

Syntax

Buffer.alloc(bufferLength, value);

bufferLength is an integer specifying the length of buffer to be created. The buffer contains all memory locations filled with value.

Node.js – Write to Buffer

There are many methods of Buffer class to write data of different formats to a buffer. In this section, we shall learn to write a string to buffer.

To write string a buffer, use Buffer.write method.

Syntax

Buffer.write(string[, offset[, length]][, encoding]);
  • string starting from the offset, number of characters provided by length are written to the buffer in the encoding format specified.
  • write() method returns the number of bytes written to the buffer.

Node.js – Read from Buffer

To read bytes from a buffer, use Buffer.values method.

Syntax

Buffer.values();

Creates and returns an iterator for buf1 values (bytes). This function is called automatically when a Buffer is used in a for..of statement.

Conclusion :

In this Node.js TutorialNode.js Buffers, we have learnt to create, write to and read Buffers in Node.js. In our next tutorials, we shall learn some interesting operations with Buffers.