Buffers handle binary data in Node.js. Here's how to use them effectively.
Creating Buffers
Reading and Writing
String Encoding
Buffer Manipulation
Working with Files
Binary Protocols
Crypto Operations
ArrayBuffer Interop
Performance Tips
Best Practices
Memory:
✓ Use Buffer.alloc for sensitive data
✓ Use Buffer.allocUnsafe for performance
✓ Pool buffers when allocating many
✓ Clear sensitive data when done
Encoding:
✓ Always specify encoding
✓ Use Buffer.byteLength for string sizes
✓ Handle multi-byte characters properly
✓ Validate input encodings
Safety:
✓ Check bounds before reading
✓ Use slice/subarray carefully
✓ Copy when sharing externally
✓ Zero sensitive buffers
Performance:
✓ Avoid unnecessary conversions
✓ Use concat over += for binary
✓ Pre-allocate when size is known
✓ Stream large data
Conclusion
Buffers are essential for binary data in Node.js. Understand encoding conversions, use appropriate read/write methods for data types, and be mindful of memory sharing. Use Buffer.alloc for security, allocUnsafe for performance, and always validate bounds when working with binary protocols.