DeployU
Interviews / Backend Engineering / What is the `Buffer` class and what is it used for in Node.js?

What is the `Buffer` class and what is it used for in Node.js?

conceptual Core Concepts Interactive Quiz Code Examples

The Scenario

You are a backend engineer at a social media company. You are building a new service that needs to interact with a TCP server that sends and receives binary data.

You need to find a way to handle this binary data in your Node.js application.

The Challenge

Explain what the Buffer class is in Node.js and why it is useful for this use case. What are the key methods of the Buffer class, and how would you use them to read and write binary data?

Wrong Approach

A junior engineer might try to handle the binary data as a string. This would not work, because strings in JavaScript are not designed to handle binary data. They might not be aware of the `Buffer` class, which is the correct tool for this job.

Right Approach

A senior engineer would know that the `Buffer` class is the key to handling binary data in Node.js. They would be able to explain what a `Buffer` is and how to use it to read and write binary data.

Step 1: Understand What a Buffer Is

A Buffer is a global class in Node.js that is used to handle binary data. It is similar to an array of integers, but it corresponds to a raw memory allocation outside the V8 heap.

Step 2: The Key Methods of the Buffer Class

MethodDescription
Buffer.from()Creates a new Buffer from a string, array, or another Buffer.
buf.write()Writes a string to a Buffer.
buf.toString()Decodes a Buffer into a string.
buf.readInt8()Reads a signed 8-bit integer from a Buffer.
buf.writeInt8()Writes a signed 8-bit integer to a Buffer.

Step 3: Read and Write Binary Data

Here’s how we can use the Buffer class to read and write binary data from a TCP socket:

const net = require('net');

const client = net.createConnection({ port: 8124 }, () => {
  // Create a buffer with a single byte
  const buf = Buffer.from([0x1]);

  // Write the buffer to the socket
  client.write(buf);
});

client.on('data', (data) => {
  // Read the first byte from the buffer
  const byte = data.readInt8(0);

  console.log('Received:', byte);
});

By using the Buffer class, we can easily read and write binary data in our Node.js application.

Practice Question

You are working with a stream of binary data and you want to convert it to a string. Which of the following would you use?