Node.js Buffer Module
π§© Node.js β Buffer Module
The Buffer module in Node.js is used to handle binary data directly.
Buffers are especially useful for reading/writing files, TCP streams, and network communications.
-
Buffers are raw memory allocations outside the V8 heap.
-
They allow working with bytes rather than strings.
Buffer is a global object, so you donβt need to require() it.
β 1. Create a Buffer
A. From string
Output:
B. Allocate a buffer of fixed size
C. Allocate unsafe buffer (faster, but may contain old data)
β Avoid using uninitialized data directly.
D. From an array of bytes
Output:
β 2. Write Data to Buffer
Output:
β 3. Read Data from Buffer
β 4. Buffer Length
β 5. Concatenate Buffers
Output:
β 6. Compare Buffers
β 7. Copy Buffers
Output:
β 8. Slice Buffers
Output:
β 9. Check if Object is Buffer
β 10. Encoding Types
Common encodings supported by Buffer:
| Encoding | Description |
|---|---|
| utf8 | Default string encoding |
| ascii | 7-bit ASCII characters |
| base64 | Base64 encoding |
| hex | Hexadecimal representation |
| latin1 | 8-bit characters |
π― Advantages of Buffer
-
Efficiently store binary data
-
Handle large files and streams
-
Work with network protocols
-
Compatible with fs module and TCP sockets
