Node.js Buffer Module

🧩 Node.js – Buffer Module

The Buffer module in Node.js is used to handle binary data directly.
Buffers are especially useful for reading/writing files, TCP streams, and network communications.

  • Buffers are raw memory allocations outside the V8 heap.

  • They allow working with bytes rather than strings.

Buffer is a global object, so you don’t need to require() it.


βœ… 1. Create a Buffer

A. From string

const buf = Buffer.from("Hello Node.js");
console.log(buf);

Output:

<Buffer 48 65 6c 6c 6f 20 4e 6f 64 65 2e 6a 73>

B. Allocate a buffer of fixed size

const buf = Buffer.alloc(10); // 10 bytes
console.log(buf);

C. Allocate unsafe buffer (faster, but may contain old data)

const buf = Buffer.allocUnsafe(10);
console.log(buf);

⚠ Avoid using uninitialized data directly.


D. From an array of bytes

const buf = Buffer.from([72, 101, 108, 108, 111]);
console.log(buf.toString());

Output:

Hello

βœ… 2. Write Data to Buffer

const buf = Buffer.alloc(10);
buf.write("Node");
console.log(buf.toString());

Output:

Node

βœ… 3. Read Data from Buffer

const buf = Buffer.from("Hello Node.js");
console.log(buf.toString()); // "Hello Node.js"
console.log(buf.toString("utf8")); // specify encoding
console.log(buf.toString("hex")); // hexadecimal format

βœ… 4. Buffer Length

const buf = Buffer.from("Hello");
console.log(buf.length); // 5 bytes

βœ… 5. Concatenate Buffers

const buf1 = Buffer.from("Hello ");
const buf2 = Buffer.from("World");
const buf3 = Buffer.concat([buf1, buf2]);
console.log(buf3.toString());

Output:

Hello World

βœ… 6. Compare Buffers

const buf1 = Buffer.from("ABC");
const buf2 = Buffer.from("ABD");
console.log(buf1.compare(buf2)); // -1 (buf1 < buf2)


βœ… 7. Copy Buffers

const buf1 = Buffer.from("Hello");
const buf2 = Buffer.alloc(10);
buf1.copy(buf2);
console.log(buf2.toString());

Output:

Hello

βœ… 8. Slice Buffers

const buf = Buffer.from("Hello Node.js");
const buf2 = buf.slice(6, 10);
console.log(buf2.toString());

Output:

Node

βœ… 9. Check if Object is Buffer

const buf = Buffer.from("Test");
console.log(Buffer.isBuffer(buf)); // true

βœ… 10. Encoding Types

Common encodings supported by Buffer:

Encoding Description
utf8 Default string encoding
ascii 7-bit ASCII characters
base64 Base64 encoding
hex Hexadecimal representation
latin1 8-bit characters

🎯 Advantages of Buffer

  • Efficiently store binary data

  • Handle large files and streams

  • Work with network protocols

  • Compatible with fs module and TCP sockets


πŸ”Ή Example: Reading File as Buffer

const fs = require("fs");

const data = fs.readFileSync(“example.txt”); // returns Buffer
console.log(data);
console.log(data.toString());

You may also like...