typescriptintermediate
Buffer and Binary Data
Work with binary data using Node.js Buffer: create, convert, slice, encode/decode, and compare.
typescriptPress ⌘/Ctrl + Shift + C to copy
// Create buffers
const fromString = Buffer.from('Hello, World!');
const fromArray = Buffer.from([72, 101, 108, 108, 111]);
const fromHex = Buffer.from('48656c6c6f', 'hex');
const allocated = Buffer.alloc(16); // zero-filled
const unsafe = Buffer.allocUnsafe(16); // uninitialized (faster)
console.log('From string:', fromString);
console.log('From array:', fromArray.toString());
console.log('From hex:', fromHex.toString());
// Encoding conversions
const text = 'Hello, 🌍!';
const utf8 = Buffer.from(text, 'utf-8');
console.log('\nUTF-8 bytes:', utf8.length);
console.log('As hex:', utf8.toString('hex'));
console.log('As base64:', utf8.toString('base64'));
console.log('As base64url:', utf8.toString('base64url'));
// Base64 encode/decode
function toBase64(str: string): string {
return Buffer.from(str).toString('base64');
}
function fromBase64(b64: string): string {
return Buffer.from(b64, 'base64').toString('utf-8');
}
const encoded = toBase64('secret data');
console.log('\nBase64:', encoded);
console.log('Decoded:', fromBase64(encoded));
// Buffer operations
const buf = Buffer.alloc(8);
buf.writeUInt32BE(0x12345678, 0); // Big-endian
buf.writeUInt32LE(0xdeadbeef, 4); // Little-endian
console.log('\nBuffer:', buf.toString('hex'));
console.log('Read BE:', buf.readUInt32BE(0).toString(16));
console.log('Read LE:', buf.readUInt32LE(4).toString(16));
// Float
const floatBuf = Buffer.alloc(4);
floatBuf.writeFloatBE(3.14);
console.log('Float:', floatBuf.readFloatBE().toFixed(2));
// Slice and copy
const original = Buffer.from('Hello, World!');
const slice = original.subarray(0, 5);
console.log('\nSlice:', slice.toString()); // Hello
const copy = Buffer.alloc(5);
original.copy(copy, 0, 7, 12);
console.log('Copy:', copy.toString()); // World
// Concatenate
const combined = Buffer.concat([
Buffer.from('Hello '),
Buffer.from('World'),
]);
console.log('Concat:', combined.toString());
// Compare
const a = Buffer.from('abc');
const b = Buffer.from('abc');
const c = Buffer.from('def');
console.log('\nEqual:', a.equals(b)); // true
console.log('Compare:', a.compare(c)); // -1 (a < c)
// Search
const haystack = Buffer.from('Hello World Hello');
console.log('IndexOf:', haystack.indexOf('World')); // 6
console.log('Includes:', haystack.includes('World')); // true
// Iterate
console.log('\nBytes:');
for (const byte of fromString.subarray(0, 5)) {
console.log(` ${byte} (${String.fromCharCode(byte)})`);
}Use Cases
- Binary protocol implementation
- Base64 encoding/decoding
- Low-level data manipulation
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
typescriptadvanced
Node.js Worker Threads for Parallel Processing
Use Worker Threads to run CPU-intensive tasks in parallel without blocking the event loop.
Best for: CPU-intensive data processing without blocking
#nodejs#worker-threads
typescriptintermediate
Node.js Stream Pipeline with Transform
Build efficient data processing pipelines using Node.js streams for large file handling.
Best for: Processing large CSV files without loading into memory
#nodejs#streams
typescriptintermediate
TypeScript Typed Event Emitter
Create type-safe event emitters in Node.js with full TypeScript support and autocomplete.
Best for: Type-safe pub/sub communication between modules
#nodejs#events
typescriptintermediate
Node.js Graceful Shutdown Handler
Implement graceful shutdown to properly close connections and finish requests before exit.
Best for: Production Node.js server reliability
#nodejs#shutdown