javascript / expert
Snippet
Managing Side-Effects with FinalizationRegistry
FinalizationRegistry allows you to request a callback after an object has been garbage collected. This is useful for cleaning up external resources, like file descriptors or sockets, that are tied to a JavaScript object's lifecycle without creating memory leaks.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
const registry = new FinalizationRegistry(heldValue => {console.log(`Resource ${heldValue} was garbage collected.`);});function createComplexResource(id) {const resource = { id, data: new Array(1000).fill('data') };registry.register(resource, id);return resource;}let myResource = createComplexResource('db-connection-1');myResource = null; // Eligible for GC
nodejs
Breakdown
1
new FinalizationRegistry(heldValue => { ... })
Defines the cleanup logic to run when a registered object is reclaimed.
2
registry.register(resource, id)
Associates a target object with a value (heldValue) to be passed to the cleanup callback.
3
myResource = null;
Removes the only reference to the object, allowing the engine to reclaim it eventually.