Buffer in Node.js

📘 Node.js 👁 51 views 📅 Nov 05, 2025
⏱ Estimated reading time: 2 min

A Buffer in Node.js is a data structure used to handle raw binary data directly in memory.
It is especially useful when working with streams, files, and network operations.


1. Why Buffers Are Needed

JavaScript strings handle text, not binary data.
Node.js uses Buffers to work with:

  • Files

  • TCP streams

  • Images, audio, video

  • Network packets


2. What Makes Buffers Special

  • Stores data outside the V8 heap

  • Fixed-size and memory efficient

  • Handles raw bytes

  • Faster than strings for binary data


3. Creating Buffers

3.1 Using Buffer.alloc()

Creates a buffer with initialized memory.

const buf = Buffer.alloc(10);

3.2 Using Buffer.from()

Creates a buffer from existing data.

const buf1 = Buffer.from('Node'); const buf2 = Buffer.from([65, 66, 67]);

3.3 (Avoid) Buffer.allocUnsafe()

Faster but may contain old memory data.

const buf = Buffer.allocUnsafe(10);

4. Writing and Reading Buffer Data

const buf = Buffer.alloc(10); buf.write('Hi'); console.log(buf.toString());

5. Buffer Encoding

Common encodings:

  • utf8 (default)

  • ascii

  • base64

  • hex

Buffer.from('Hello', 'utf8');

6. Buffer Methods

MethodPurpose
buf.lengthBuffer size
buf.toString()Convert to string
buf.slice()Extract part
buf.copy()Copy data
Buffer.concat()Merge buffers

7. Buffers with Streams

Streams transfer data as buffers.

readStream.on('data', chunk => { console.log(Buffer.isBuffer(chunk)); // true });

8. Buffer vs Stream

BufferStream
Holds data in memoryProcesses data in chunks
Fixed sizeContinuous flow
Not ideal for large dataIdeal for large data

9. Real-World Use Cases

  • File system operations

  • Network communication

  • Image and video processing

  • Data encoding/decoding


10. Best Practices

  • Prefer Buffer.alloc() over allocUnsafe()

  • Avoid storing large data in buffers

  • Use streams for large files


11. Summary

  • Buffers handle raw binary data in Node.js

  • Stored outside JavaScript heap

  • Essential for streams and low-level I/O

  • Faster and memory-efficient



🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes