Node.js – Buffer Module
Subject: nodejs
Node.js – Buffer Module
In Node.js, the Buffer module provides a way to work with binary data directly. Buffers are useful for file streams, network communications, and any task where you need to manipulate raw memory.
Buffers are part of the global scope—no import is needed.
Why Buffers Are Needed
In JavaScript (browser), data is usually handled as strings or objects. But in Node.js, binary streams (e.g., TCP packets, files) require low-level memory manipulation.
Buffers allow you to:
- Read and write raw binary data
- Interface with file systems, sockets, or streams
- Handle large or partial data chunks efficiently
Creating Buffers
1. Buffer.alloc(size)
Creates a zero-filled buffer:
2. Buffer.from(string)
Creates a buffer from a string:
3. Buffer.from(array)
Creates a buffer from an array of bytes:
Writing to Buffers
Reading from Buffers
Example: Concatenating Buffers
Example: Comparing Buffers
Real-World Usage Example (Streams)
Key Takeaways
- Buffers handle binary data in Node.js.
- Ideal for file I/O, stream handling, and network programming.
- Faster and more efficient than using strings for large data.
- Use
Buffer.from()
andBuffer.alloc()
to create buffers.