Node.js Buffers Practice Questions with Solutions

Introduction

Buffers are used in Node.js to work with raw binary data. They are especially important when handling files, network connections, streams, images, videos, and other data that is not simple text. In this chapter, you will practice creating Buffers, converting text to Buffers, reading and modifying Buffer values, working with encodings, combining Buffers, comparing data, and using Buffers with streams through simple step-by-step examples. Node.js Buffers Practice questions with solutions help to understand the concepts.

Question 1: How do you create a Buffer from a string?

Problem

Create a Buffer from the string "Hello Node.js" and display both the Buffer and its original text.

Solution

const message = "Hello Node.js";

const buffer = Buffer.from(message);

console.log(buffer);

console.log(buffer.toString());

Output

<Buffer 48 65 6c 6c 6f 20 4e 6f 64 65 2e 6a 73>
Hello Node.js

The exact Buffer formatting may vary slightly depending on the Node.js version.

Step-by-Step Explanation

First, create a normal string:

const message = "Hello Node.js";

Convert it into a Buffer:

const buffer = Buffer.from(message);

Node.js stores the characters as binary byte values.

To convert the Buffer back to readable text:

buffer.toString();

Question 2: How do you check the size of a Buffer?

Problem

Create a Buffer containing "Node.js" and find its size in bytes.

Solution

const buffer = Buffer.from("Node.js");

console.log("Buffer:", buffer);

console.log("Size:", buffer.length, "bytes");

Output

Buffer: <Buffer 4e 6f 64 65 2e 6a 73>
Size: 7 bytes

Step-by-Step Explanation

The string:

Node.js

contains seven characters.

We create the Buffer:

const buffer = Buffer.from("Node.js");

The .length property gives the number of bytes:

buffer.length

Therefore:

7 bytes

Question 3: How do you convert a Buffer back to a string?

Problem

Create a Buffer and convert it back into normal text.

Solution

const buffer = Buffer.from("Welcome to Node.js");

const message = buffer.toString();

console.log(message);

Output

Welcome to Node.js

Step-by-Step Explanation

The Buffer is created using:

const buffer = Buffer.from(
    "Welcome to Node.js"
);

To convert it back to text:

buffer.toString();

We store the result:

const message = buffer.toString();

Then display it:

console.log(message);

Question 4: How do you create an empty Buffer?

Problem

Create a Buffer with space for 10 bytes and display its size.

Solution

const buffer = Buffer.alloc(10);

console.log(buffer);

console.log(
    "Buffer size:",
    buffer.length,
    "bytes"
);

Output

<Buffer 00 00 00 00 00 00 00 00 00 00>
Buffer size: 10 bytes

Step-by-Step Explanation

We create a Buffer containing 10 bytes:

const buffer = Buffer.alloc(10);

Buffer.alloc() creates a new Buffer and initializes its memory.

The size is:

buffer.length

which is:

10 bytes

Why use Buffer.alloc()?

It is useful when you know in advance how much Buffer space you need.

For example:

const buffer = Buffer.alloc(100);

creates a Buffer with 100 bytes.


Question 5: How do you read and modify individual Buffer values?

Problem

Create a Buffer from "ABC", display its byte values, change the first byte, and display the result.

Solution

const buffer = Buffer.from("ABC");

console.log("Original:", buffer.toString());

console.log("First byte:", buffer[0]);

buffer[0] = 68;

console.log("Updated:", buffer.toString());

Output

Original: ABC
First byte: 65
Updated: DBC

Step-by-Step Explanation

The Buffer contains:

A B C

We access the first byte:

buffer[0]

The character A has the UTF-8 byte value:

65

Then we change it:

buffer[0] = 68;

The byte value 68 represents:

D

Therefore the Buffer becomes:

DBC

Question 6: How do you use different Buffer encodings?

Problem

Create a Buffer from a string and convert it back using UTF-8 and Base64.

Solution

const message = "Hello Node.js";

const buffer = Buffer.from(
    message,
    "utf8"
);

console.log("UTF-8:");

console.log(
    buffer.toString("utf8")
);

console.log("Base64:");

console.log(
    buffer.toString("base64")
);

Output

UTF-8:
Hello Node.js

Base64:
SGVsbG8gTm9kZS5qcw==

Step-by-Step Explanation

We create a Buffer using UTF-8:

const buffer = Buffer.from(
    message,
    "utf8"
);

We can read it as UTF-8:

buffer.toString("utf8");

We can also encode the same bytes as Base64:

buffer.toString("base64");

Cmat, not encryption. A Base64 string can be decoded back into the original data.


Question 7: How do you combine two Buffers?

Problem

Create two Buffers and combine them into a single Buffer.

Solution

const first = Buffer.from("Hello ");

const second = Buffer.from("Node.js");

const combined = Buffer.concat([
    first,
    second
]);

console.log(combined.toString());

Output

Hello Node.js

Step-by-Step Explanation

First Buffer:

const first = Buffer.from("Hello ");

Second Buffer:

const second = Buffer.from("Node.js");

We combine them using:

Buffer.concat([
    first,
    second
]);

The result is stored in:

const combined

Finally:

combined.toString();

converts the combined Buffer into readable text.


Question 8: How do you compare two Buffers?

Problem

Create two Buffers and check whether they contain the same data.

Solution

const buffer1 = Buffer.from("Node.js");

const buffer2 = Buffer.from("Node.js");

const buffer3 = Buffer.from("Python");

console.log(
    "Buffer 1 and Buffer 2:",
    buffer1.equals(buffer2)
);

console.log(
    "Buffer 1 and Buffer 3:",
    buffer1.equals(buffer3)
);

Output

Buffer 1 and Buffer 2: true
Buffer 1 and Buffer 3: false

Step-by-Step Explanation

We create two identical Buffers:

const buffer1 = Buffer.from("Node.js");

const buffer2 = Buffer.from("Node.js");

We compare them:

buffer1.equals(buffer2);

The result is:

true

Now compare with a different Buffer:

buffer1.equals(buffer3);

The result is:

false

Question 9: How do you use Buffers with a file?

Problem

Read a file as a Buffer and display its content after converting it to text.

Solution

First create message.txt:

Node.js Buffers are useful for binary data.

Create index.js:

const fs = require("fs");

fs.readFile("message.txt", (error, data) => {

    if (error) {

        console.log(
            "Error:",
            error.message
        );

        return;
    }

    console.log("Buffer:");

    console.log(data);

    console.log("File content:");

    console.log(data.toString());
});

Output

You will see something similar to:

Buffer:
<Buffer 4e 6f 64 65 2e 6a 73 ...>

File content:
Node.js Buffers are useful for binary data.

The exact Buffer output depends on the file content.

Step-by-Step Explanation

fs.readFile() returns file data as a Buffer when an encoding is not specified:

fs.readFile("message.txt", (error, data) => {

The data variable contains a Buffer.

We can display it:

console.log(data);

Or convert it into readable text:

console.log(data.toString());

Question 10: How do you process a file using Buffers and Streams?

Problem

Read a file using a stream, count the total number of bytes received, and display the result when reading is complete.

Solution

Create large-file.txt:

Node.js streams provide data in chunks.
Buffers allow Node.js to work with raw binary data.

Create index.js:

const fs = require("fs");

const readStream = fs.createReadStream(
    "large-file.txt"
);

let totalBytes = 0;

readStream.on("data", (chunk) => {

    console.log(
        "Received chunk:",
        chunk.length,
        "bytes"
    );

    totalBytes += chunk.length;
});

readStream.on("end", () => {

    console.log(
        "Total bytes:",
        totalBytes
    );

});

readStream.on("error", (error) => {

    console.log(
        "Error:",
        error.message
    );

});

Output

The exact number of chunks depends on the file size and stream buffering.

For example:

Received chunk: 98 bytes
Total bytes: 98

For a larger file, you may see:

Received chunk: 65536 bytes
Received chunk: 65536 bytes
Received chunk: 24320 bytes
Total bytes: 155392

The exact values will vary.

Step-by-Step Explanation

fs.createReadStream() reads the file progressively:

const readStream = fs.createReadStream(
    "large-file.txt"
);

Each data event provides a chunk.

That chunk is typically a Buffer:

readStream.on("data", (chunk) => {

We can find the number of bytes:

chunk.length

Then add them:

totalBytes += chunk.length;

When the stream finishes:

readStream.on("end", () => {

we display the total.

Key Takeaways

  • A Buffer is used by Node.js to work with raw binary data.
  • Buffers are especially important for files, streams, network communication, images, videos, and other binary data.
  • Buffer.from() creates a Buffer from existing data.
  • Buffer.alloc() creates a new initialized Buffer with a specified size.
  • Buffer.length returns the number of bytes in a Buffer.
  • Buffer indexes start at 0.
  • Individual Buffer bytes can be read and modified using indexes.
  • Buffer.toString() converts Buffer data into readable text.
  • UTF-8 is the default encoding commonly used for text.
  • Base64 and hexadecimal are useful representations of binary data.
  • Base64 is an encoding format, not encryption.
  • Buffer.concat() combines multiple Buffers.
  • Buffer.equals() checks whether two Buffers contain the same bytes.
  • fs.readFile() returns a Buffer when no encoding is specified.
  • Stream data events commonly provide chunks as Buffers.
  • chunk.length can be used to determine the number of bytes in a Buffer chunk.
  • Buffers allow Node.js to handle binary data efficiently.
  • Buffers and Streams are closely related in Node.js.
  • Understanding Buffers makes file and network programming easier to understand.
  • Buffers are an important foundation for advanced Node.js concepts such as file uploads, HTTP streams, and binary data processing.

FAQs

1. What is a Buffer in Node.js?

A Buffer is a Node.js object used to work with raw binary data.

For example:

const buffer = Buffer.from("Hello");

The Buffer stores the underlying byte representation of the data.

Buffers are commonly used with files, streams, network connections, images, and other binary data.

2. What is the difference between a String and a Buffer?

A String represents text:

const message = "Hello";

A Buffer represents bytes:

const buffer = Buffer.from("Hello");

You can convert the Buffer back to text:

buffer.toString();

Buffers are particularly useful when working with binary data.

3. What does Buffer.from() do?

Buffer.from() creates a Buffer from existing data.

Example:

const buffer = Buffer.from(
    "Hello Node.js"
);

It can also accept an encoding:

const buffer = Buffer.from(
    "Hello",
    "utf8"
);

4. What is Buffer.alloc() used for?

Buffer.alloc() creates a new Buffer with a specified size.

Example:

const buffer = Buffer.alloc(10);

This creates a Buffer containing 10 bytes.

It is useful when you need a new initialized Buffer with a known size.

5. How do I convert a Buffer to a string?

Use toString():

const buffer = Buffer.from("Hello");

const message = buffer.toString();

console.log(message);

Output:

Hello

You can also specify an encoding:

buffer.toString("base64");

6. Can Buffers store images and other binary files?

Yes.

Buffers can represent raw binary data from files such as:

  • Images
  • PDFs
  • Audio
  • Video
  • ZIP files
  • Other binary files

For example, Node.js can read a binary file into a Buffer:

const fs = require("fs");

const data = fs.readFileSync(
    "image.png"
);

console.log(data);

You should not convert arbitrary binary data to normal text unless you specifically need a textual encoding.

7. How are Buffers related to Streams?

Streams often provide data in chunks, and those chunks are commonly represented as Buffers.

For example:

const fs = require("fs");

const stream = fs.createReadStream(
    "large-file.txt"
);

stream.on("data", (chunk) => {

    console.log(
        "Received:",
        chunk.length,
        "bytes"
    );

});

The chunk contains a portion of the file data.

This relationship is important because Streams handle the flow of data while Buffers represent the raw bytes being transferred or processed.

Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.

Scroll to Top