Buffers handle binary data in Node.js. Here's how to work with them effectively.
Creating Buffers#
Encodings#
Reading and Writing#
Slicing and Copying#
Concatenation#
Comparison#
Searching#
Iteration#
Conversion#
Base64 Encoding#
Working with Files#
Network Operations#
TypedArray Interop#
Best Practices#
Creation:
✓ Use Buffer.alloc for security
✓ Use Buffer.from for conversion
✓ Specify encoding explicitly
✓ Use allocUnsafe only when needed
Memory:
✓ Reuse buffers when possible
✓ Use slice carefully (shares memory)
✓ Pool buffers for frequent allocation
✓ Watch for memory leaks
Performance:
✓ Pre-allocate known sizes
✓ Use streams for large data
✓ Batch small writes
✓ Use TypedArrays when appropriate
Avoid:
✗ new Buffer() (deprecated)
✗ allocUnsafe without filling
✗ Assuming encoding
✗ Ignoring byte order
Conclusion#
Buffers are essential for binary data handling in Node.js. Use them for file I/O, network protocols, cryptography, and any binary processing. Understand endianness for cross-platform compatibility, use appropriate encodings, and be mindful of memory sharing with slices. For large data, prefer streams over loading entire files into buffers.