Buffer in Node.js
⏱ 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.
3.2 Using Buffer.from()
Creates a buffer from existing data.
3.3 (Avoid) Buffer.allocUnsafe()
Faster but may contain old memory data.
4. Writing and Reading Buffer Data
5. Buffer Encoding
Common encodings:
-
utf8(default) -
ascii -
base64 -
hex
6. Buffer Methods
| Method | Purpose |
|---|---|
buf.length | Buffer 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.
8. Buffer vs Stream
| Buffer | Stream |
|---|---|
| Holds data in memory | Processes data in chunks |
| Fixed size | Continuous flow |
| Not ideal for large data | Ideal 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()overallocUnsafe() -
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
Register Now
Share this Post
← Back to Tutorials