In browser JavaScript, strings are UTF-16 encoded, which is ideal for displaying text. However, servers must handle raw TCP network packets, cryptographic hashes, video streams, and image binaries. The Buffer class was created in Node.js to allocate raw binary memory outside of V8's garbage-collected heap.
In modern Node.js, the legacy new Buffer() constructor is deprecated due to security vulnerabilities. You should always use the static factory methods:
Buffer.from() (Creating from Existing Data)// Create a buffer from a UTF-8 string
const buf1 = Buffer.from('Veewom');
console.log(buf1);
// Output: <Buffer 56 65 65 77 6f 6d> (Hexadecimal ASCII values)
// Convert buffer back to string
console.log('Decoded String:', buf1.toString('utf8')); // 'Veewom'
console.log('Hex Format:', buf1.toString('hex')); // '566565776f6d'
console.log('Base64:', buf1.toString('base64')); // 'VmVld29t'
Buffer.alloc(size) (Zero-Filled Safe Allocation)// Allocate a clean 10-byte buffer filled with zeros
const safeBuf = Buffer.alloc(10);
console.log(safeBuf);
// <Buffer 00 00 00 00 00 00 00 00 00 00>
// Write data into the allocated buffer
safeBuf.write('Node');
console.log(safeBuf);
// <Buffer 4e 6f 64 65 00 00 00 00 00 00>
Buffer.allocUnsafe(size) (High-Speed Raw Memory)// Fast allocation without zero-filling (Contains whatever garbage was in memory!)
const unsafeBuf = Buffer.allocUnsafe(10);
// You MUST overwrite all bytes immediately before using:
unsafeBuf.fill(0);
Buffers are standard for handling Base64 strings in authorization headers and data URLs:
// Basic Auth Encoding Example
const username = 'admin';
const password = 'SecretPassword123';
const credentials = `${username}:${password}`;
// Encode to Base64
const base64Auth = Buffer.from(credentials).toString('base64');
console.log('Authorization: Basic', base64Auth);
// Output: Authorization: Basic YWRtaW46U2VjcmV0UGFzc3dvcmQxMjM=
// Decode from Base64
const decodedCredentials = Buffer.from(base64Auth, 'base64').toString('utf8');
console.log('Decoded:', decodedCredentials);
// Output: admin:SecretPassword123
When you slice a Buffer with buf.subarray(start, end), it creates a view over the same underlying memory without making a copy. Modifying the slice modifies the original buffer:
const original = Buffer.from('ABCDEF');
const slice = original.subarray(0, 3); // 'ABC'
slice[0] = 90; // ASCII 'Z'
console.log('Slice:', slice.toString()); // 'ZBC'
console.log('Original:', original.toString()); // 'ZBCDEF' (Mutated!)
Boost your server-side JavaScript proficiency by studying these closely connected core modules:
Streams transport data as raw binary Buffer chunks.
Hash and cipher operations require raw Buffers.
Reading files without utf8 encoding returns Buffers.