Buffer Module

Buffer Module

A Buffer is a temporary storage area in memory that stores raw binary data (zeros and ones). While JavaScript is excellent at handling strings, it historically had no mechanism for manipulating streams of raw binary data (like images, PDF files, or network packets). The Buffer module solves this problem.

Whenever you read a file or receive streaming data over the network, that data arrives as a Buffer.


1. Using the Buffer Class

The Buffer class is globally available, meaning you do not need to require('buffer') to use it.

You can allocate memory for a new buffer, or convert an existing string into a buffer using Buffer.from().

Creating and Reading Buffers

// Create a buffer from a simple string
const myBuffer = Buffer.from('Hello');

// When printed, it shows raw hexadecimal data console.log(myBuffer); // Output: <Buffer 48 65 6c 6c 6f>

// Convert the buffer back into a human-readable string console.log(myBuffer.toString()); // Output: "Hello"


2. Real-World Use Cases

You typically interact with Buffers indirectly. For instance, when using the fs module to read a file without specifying 'utf8' encoding, the return value is a Buffer:

const fs = require('fs');

fs.readFile('document.txt', (err, data) => { // 'data' is a Buffer! console.log(data); // <Buffer ...>

// Convert to string to see the text console.log(data.toString()); });


Exercise

?

How do you convert a Buffer object back into human-readable text?