Lesson 28 of 50 – Buffers

56% Completed
56%

Buffers in Node.js

A Buffer in Node.js is used to work with binary data. Buffers are especially useful when handling files, images, network packets, and other data that is not simply text.

Remember: A Buffer represents a sequence of bytes. Node.js provides the built-in Buffer class for creating, reading, writing, and converting binary data.

1. What Is a Buffer?

Computers store data as bytes. A Buffer provides a way to work directly with those bytes in Node.js.

Buffers are commonly used for:

  • Reading and writing files.
  • Processing images, audio, and video data.
  • Handling TCP network data.
  • Converting text into bytes and bytes back into text.
  • Processing binary data from APIs and streams.
Example: Creating a Buffer
const buffer = Buffer.from("Hello");

console.log(buffer);
Output:
<Buffer 48 65 6c 6c 6f>

The string "Hello" is converted into five UTF-8 bytes. Each hexadecimal value represents one byte.

2. Creating a Buffer from a String

Use Buffer.from() to create a Buffer from a string, array, or another supported data source.

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

console.log(buffer);
console.log(buffer.length);
Output:
<Buffer 4e 6f 64 65 2e 6a 73>
7

The string "Node.js" contains seven ASCII characters, so its UTF-8 Buffer has seven bytes.

3. Creating an Empty Buffer

Use Buffer.alloc() to create a Buffer of a specified size. It initializes the allocated bytes to zero.

Example: Buffer.alloc()
const buffer = Buffer.alloc(5);

console.log(buffer);
console.log(buffer.length);
Output:
<Buffer 00 00 00 00 00>
5

This creates a Buffer containing five zero-valued bytes. Buffer.alloc() is a safe choice when you need a new Buffer initialized to zero.

4. Converting a Buffer to a String

Use the toString() method to convert Buffer data into text using an appropriate character encoding.

Example: Buffer to String
const buffer = Buffer.from("Welcome");

const text = buffer.toString();

console.log(text);
Output:
Welcome

By default, toString() decodes Buffer data as UTF-8.

5. Accessing Buffer Elements

You can access individual bytes using their index. Buffer indexes start at zero, and each byte has a value from 0 to 255.

Example: Reading Bytes
const buffer = Buffer.from("ABC");

console.log(buffer[0]);
console.log(buffer[1]);
console.log(buffer[2]);
Output:
65
66
67

The UTF-8 byte values for A, B, and C are 65, 66, and 67.

6. Modifying Buffer Data

Buffer elements can be changed by assigning a new byte value to a valid index.

Example: Changing a Byte
const buffer = Buffer.from("ABC");

buffer[0] = 68;

console.log(buffer.toString());
Output:
DBC

The byte value 68 represents the letter D in ASCII and UTF-8. Assigning a value outside the byte range does not store that original value unchanged.

7. Buffer Length

The length property returns the number of bytes in a Buffer. It does not necessarily return the number of characters in the original string.

Example: Byte Length
const buffer = Buffer.from("Hello");

console.log(buffer.length);
Output:
5

"Hello" uses five bytes in UTF-8.

8. Buffer and Unicode Characters

Some characters require more than one byte in UTF-8. Therefore, the number of bytes in a Buffer can be greater than the number of characters in a string.

Example: Unicode Byte Length
const text = "A😊";
const buffer = Buffer.from(text);

console.log(buffer.length);
console.log(buffer.toString());
Output:
5
A😊

The letter A uses one UTF-8 byte, while the emoji 😊 uses four UTF-8 bytes. Together they require five bytes.

9. Buffer and File System

Node.js can read file contents into a Buffer. This is useful when working with binary files or when you need to process the bytes directly.

Example: Reading a File into a Buffer
const fs = require("fs");

fs.readFile("student.txt", function(error, data) {
    if (error) {
        console.log("Error:", error.message);
        return;
    }

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

If student.txt contains the text Hello Student, the callback receives a Buffer containing the file data.

When no encoding is supplied to fs.readFile(), the data argument is a Buffer.

10. Important Buffer Methods

Method or Property Purpose Example
Buffer.from() Creates a Buffer from supplied data. Buffer.from("Hi")
Buffer.alloc() Creates a zero-initialized Buffer. Buffer.alloc(10)
toString() Converts Buffer bytes into text. buffer.toString()
length Returns the number of bytes. buffer.length
Buffer.isBuffer() Checks whether a value is a Buffer. Buffer.isBuffer(buffer)
Buffer.byteLength() Calculates the byte length of input data. Buffer.byteLength("Hello")

11. Checking Whether a Value Is a Buffer

Use Buffer.isBuffer() to check whether a value is an instance of the Node.js Buffer class.

Example: Buffer.isBuffer()
const buffer = Buffer.from("Node.js");
const text = "Node.js";

console.log(Buffer.isBuffer(buffer));
console.log(Buffer.isBuffer(text));
Output:
true
false

12. Practical Assignment

Practice these programs:
  1. Create a Buffer from the string "Hello Student".
  2. Create a Buffer of 10 zero-initialized bytes.
  3. Convert a Buffer into a string.
  4. Print the byte values of the string "ABC".
  5. Change the first byte of a Buffer and print the result.
  6. Compare the character count and byte length of a Unicode string.
  7. Read a text file and display its Buffer and string contents.
  8. Use Buffer.isBuffer() to test a Buffer and a normal string.

Test Your Knowledge – Buffers

Select the correct answer for each question.

1. What is a Buffer mainly used for in Node.js?
2. Which method creates a Buffer initialized with zero-valued bytes?
3. What does buffer.length return?