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.
JavaScript strings handle text, not binary data.
Node.js uses Buffers to work with:
Files
TCP streams
Images, audio, video
Network packets
Stores data outside the V8 heap
Fixed-size and memory efficient
Handles raw bytes
Faster than strings for binary data
Buffer.alloc()Creates a buffer with initialized memory.
Buffer.from()Creates a buffer from existing data.
Buffer.allocUnsafe()Faster but may contain old memory data.
Common encodings:
utf8 (default)
ascii
base64
hex
| Method | Purpose |
|---|---|
buf.length | Buffer size |
buf.toString() | Convert to string |
buf.slice() | Extract part |
buf.copy() | Copy data |
Buffer.concat() | Merge buffers |
Streams transfer data as buffers.
| Buffer | Stream |
|---|---|
| Holds data in memory | Processes data in chunks |
| Fixed size | Continuous flow |
| Not ideal for large data | Ideal for large data |
File system operations
Network communication
Image and video processing
Data encoding/decoding
Prefer Buffer.alloc() over allocUnsafe()
Avoid storing large data in buffers
Use streams for large files
Buffers handle raw binary data in Node.js
Stored outside JavaScript heap
Essential for streams and low-level I/O
Faster and memory-efficient
Take quizzes related to this topic and see where you stand!
Start Quiz Now