Node.js uses a garbage collector that automatically frees memory for objects that are no longer referenced anywhere in the program. This helps prevent memory leaks without manual intervention.
function createBuffer() {
const buf = Buffer.alloc(10 * 1024 * 1024); // 10MB buffer
// do something with buf
}
createBuffer();Since the buffer is a local variable and not referenced outside the function, once the function ends, the buffer becomes unreachable. The garbage collector will then free its memory.
const cache = {};
function addToCache(key, value) {
cache[key] = value;
}
setInterval(() => {
addToCache(Date.now(), new Array(1000000).fill('*'));
}, 1000);The cache object grows indefinitely because old entries are never removed. This prevents the garbage collector from freeing memory, causing a memory leak.
WeakMap keys must be objects. Option A uses an object as the key and a string as the value, which is correct. Option A and D use strings as keys, which is invalid. Option A uses a new object literal as key but does not keep a reference, so it is immediately lost and not useful.
let bigBuffer = Buffer.alloc(50 * 1024 * 1024); // 50MB buffer console.log(process.memoryUsage().heapUsed); bigBuffer = null; setTimeout(() => { console.log(process.memoryUsage().heapUsed); }, 1000);
Setting the buffer variable to null removes the reference, but garbage collection runs asynchronously. The memory may not be freed immediately, so the second log may show similar or slightly higher heap usage.