【发布时间】:2021-08-06 17:27:01
【问题描述】:
在其他语言中,当对象即将被 GC 收集时,会调用终结器(也称为析构器)。这对于检测与对象生命周期相关的某些类型的错误非常有用。
有没有办法在 NodeJS 上获得这种行为——在 JS 级别,而不是通过本机接口?
【问题讨论】:
标签: node.js garbage-collection destructor finalizer
在其他语言中,当对象即将被 GC 收集时,会调用终结器(也称为析构器)。这对于检测与对象生命周期相关的某些类型的错误非常有用。
有没有办法在 NodeJS 上获得这种行为——在 JS 级别,而不是通过本机接口?
【问题讨论】:
标签: node.js garbage-collection destructor finalizer
我不相信这是 真的 JavaScript 支持的。我相信你能得到的最接近的是FinalizationRegistry
FinalizationRegistry 允许您在对象被垃圾回收时指定回调。
我们可以实现一些事情,比如完成行为:
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
【讨论】: