node.js - 当我的对象即将被 Node 中的 GC 收集时,我可以得到回调吗?
问题描述
在其他语言中,当对象即将被 GC 收集时,会调用终结器(也称为析构器)。这对于检测与对象生命周期相关的某些类型的错误非常有用。
有没有办法在 NodeJS 上获得这种行为——在 JS 级别,而不是通过本机接口?
解决方案
我不相信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
推荐阅读
- python - 为股票和指数收益建立线性回归
- c - 如何消除 GTK 中小部件和窗口角之间的间隙?
- python - 如何设置 Google Cloud Scheduler 以运行 Google Colab?
- javascript - 如何更新多个角色的权限?
- arrays - 在 main 中声明一个固定长度的二维数组时出现分段错误
- pandas - matplotlib.axis.axes 体积的 mplfinance 错误
- python - 当我的乌龟撞到精灵时,如何让我的游戏重置?
- laravel - 在laravel中不属于属于关系的地方
- javascript - 在为多管道分支作业重建时如何在詹金斯中添加单选按钮
- php - 将 php 生成的 JSON 字符串存储在 CSV 文件中