首页 > 解决方案 > 当我的对象即将被 Node 中的 GC 收集时,我可以得到回调吗?

问题描述

在其他语言中,当对象即将被 GC 收集时,会调用终结器(也称为析构器)。这对于检测与对象生命周期相关的某些类型的错误非常有用。

有没有办法在 NodeJS 上获得这种行为——在 JS 级别,而不是通过本机接口?

标签: node.jsgarbage-collectiondestructorfinalizer

解决方案


我不相信JavaScript真的支持这一点。我相信你能得到的最接近的是FinalizationRegistry

FinalizationRegistry 允许您在对象被垃圾回收时指定回调。

我们可以实现类似 finalize 行为:

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();

您需要在 Node.js 中公开 gc 函数以允许此代码工作,调用如下:

node --expose-gc app.js

推荐阅读