如何请求 node.js 中的垃圾收集器运行?

在启动时,我的 node.js 应用程序似乎使用了大约200MB 的内存。如果我将它单独放置一段时间,它将缩小到大约9MB。

有没有可能从应用程序内部:

  1. 检查应用程序使用了多少内存?
  2. 请求垃圾收集器运行?

我问这个问题的原因是,我从磁盘加载了许多文件,这些文件是临时处理的。这可能会导致内存使用量激增。但是我不想在 GC 运行之前加载更多的文件,否则就有内存不足的风险。

有什么建议吗?

81358 次浏览

One thing I would suggest, is that unless you need those files right at startup, try to load only when you need them.

EDIT: Refer to the post above.

If you launch the node process with the --expose-gc flag, you can then call global.gc() to force node to run garbage collection. Keep in mind that all other execution within your node app is paused until GC completes, so don't use it too often or it will affect performance.

You might want to include a check when making GC calls from within your code so things don't go bad if node was run without the flag:

try {
if (global.gc) {global.gc();}
} catch (e) {
console.log("`node --expose-gc index.js`");
process.exit();
}