javascript / intermediate
Snippet
Manual Memory Management with Buffers
Buffers are used to handle binary data in Node.js. Unlike strings, they point to a fixed-size memory allocation outside the V8 heap. Using .subarray() creates a view into the same memory, which is efficient but means changes to the view affect the original.
snippet.js
1
2
3
4
5
6
7
8
9
10
const buffer = Buffer.alloc(10); // Allocate 10 bytesbuffer.write('NodeJS', 0, 'utf-8');console.log(buffer.toString('hex'));const sub = buffer.subarray(0, 4);console.log(sub.toString()); // 'Node'sub.write('JS'); // Modifies the original buffer!console.log(buffer.toString()); // 'JSdeJS'
nodejs
Breakdown
1
const buffer = Buffer.alloc(10);
Creates a zero-filled buffer of 10 bytes for safe binary storage.
2
buffer.subarray(0, 4);
Creates a new Buffer view without copying the underlying memory.