Search code examples
node.jsgarbage-collectiondestructorfinalizer

Can I get a callback when my object is about to get collected by GC in Node?


In other languages, there are finalisers (also called destructors) that are called when the object is about to be collected by GC. This can be very useful to detect certain kind of bugs related to lifetimes of objects.

Is there a way to get this behaviour on NodeJS — on JS level, not through native interface?


Solution

  • I don't believe this is really supported in JavaScript.. the nearest I believe you can get is the FinalizationRegistry

    The FinalizationRegistry allows you to specify a callback when an object has been garbage collected.

    We can achieve something like finalize behavior:

    class foo {
        constructor(id) {
            this.id = id;
            const goodbye = `finalize: id: ` + id;
            this.finalize = () =>  console.log(goodbye);
        }
    }
    
    function garbageCollect() {
        try {
            console.log("garbageCollect: Collecting garbage...")
            global.gc();
        } catch (e) {
            console.log(`You must expose the gc() method => call using 'node --expose-gc app.js'`);
        }
    }
    
    let foos = Array.from( { length: 10 }, (v, k) => new foo(k + 1));
    
    const registry = new FinalizationRegistry(heldValue => heldValue());
    
    foos.forEach(foo => registry.register(foo, foo.finalize));
    
    // Orphan our foos...
    foos = null;
    
    // Our foos should be garbage collected since no reference is being held to them
    garbageCollect();
    

    You'll need to expose the gc function in Node.js to allow this code to work, call like so:

    node --expose-gc app.js