Node.js
Buffers
Work with binary data using Buffer and TypedArrays.
By EZ4Code Team
bufferbinaryencoding
Code
// Allocate buffers
const buf = Buffer.alloc(8); // zero-filled
const unsafe = Buffer.allocUnsafe(8); // uninitialized, faster
const fromStr = Buffer.from("hello", "utf8");
const fromHex = Buffer.from("48656c6c6f", "hex");
// Read and write
buf.writeUInt32BE(0x12345678, 0);
const n = buf.readUInt32BE(0);
console.log(n.toString(16)); // 12345678
// Convert between encodings
const b64 = fromStr.toString("base64");
const decoded = Buffer.from(b64, "base64").toString("utf8");
// Concat and slice
const combined = Buffer.concat([fromStr, Buffer.from("!")]);
const slice = combined.subarray(0, 3);
// Iterate bytes
for (const byte of combined) {
// byte is 0-255
}Explanation
Buffer is Node's primary binary data type, a subclass of Uint8Array backed by a chunk of raw memory. alloc initializes memory to zero for safety, while allocUnsafe skips zeroing for speed and is used internally by the runtime. Buffers convert between encodings (utf8, base64, hex) via toString and Buffer.from.
More Node.js Snippets
fs Module
Read, write, and watch files with promises and callbacks.
HTTP Server
Build an HTTP server with the http module and routing.
Streams
Pipe, transform, and consume streams efficiently.
EventEmitter
Emit and listen for custom events.
path Module
Join, resolve, and parse file paths cross-platform.
Child Process
Spawn, exec, and fork external processes.