如何要求Node.js中的垃圾收集器运行?

发布于 2025-02-10 05:24:44 字数 235 浏览 2 评论 0原文

在启动时,我的Node.js应用似乎使用了大约200MB的内存。如果我不理一会儿,它会收缩到9MB左右。

从应用程序内部到:

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

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

有什么建议吗?

At startup, it seems my node.js app uses around 200MB of memory. If I leave it alone for a while, it shrinks to around 9MB.

Is it possible from within the app to:

  1. Check how much memory the app is using ?
  2. Request the garbage collector to run ?

The reason I ask is, I load a number of files from disk, which are processed temporarily. This probably causes the memory usage to spike. But I don't want to load more files until the GC runs, otherwise there is the risk that I will run out of memory.

Any suggestions ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

温柔戏命师 2025-02-17 05:24:44

如果您使用- expose-gc flag启动节点进程,则可以调用global.gc()迫使节点运行垃圾收集。请记住,您的节点应用程序中的所有其他执行均已暂停,直到GC完成为止,因此不要经常使用它,否则会影响性能。

您可能需要在代码中拨打GC调用时包括一张检查,这样,如果没有标志的节点运行,则情况并不糟糕:

if (global.gc) {
    global.gc();
} else {
    console.log('Garbage collection unavailable.  Pass --expose-gc '
      + 'when launching node to enable forced garbage collection.');
}

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:

if (global.gc) {
    global.gc();
} else {
    console.log('Garbage collection unavailable.  Pass --expose-gc '
      + 'when launching node to enable forced garbage collection.');
}
他夏了夏天 2025-02-17 05:24:44

当您无法通过任何原因将传递给您的节点进程中时将gc flacs flak flacs flak ,您可以尝试以下操作:

import { setFlagsFromString } from 'v8';
import { runInNewContext } from 'vm';

setFlagsFromString('--expose_gc');
const gc = runInNewContext('gc'); // nocommit
gc();

注意:

  • 这在节点16.x中对我有用,
  • 您可能需要检查<<<<<<<<<<< =“ noreferrer”> process.memoryusage()
  • a href =“ https://nodejs.org/api/process.html#processmemoryusage” rel v8.setflagsfromstring

该方法应谨慎使用。 VM开始后的更改设置可能会导致不可预测的行为,包括崩溃和数据丢失;否则可能什么也不做。

When you cannot pass the --expose-gc flag to your node process on start for any reason, you may try this:

import { setFlagsFromString } from 'v8';
import { runInNewContext } from 'vm';

setFlagsFromString('--expose_gc');
const gc = runInNewContext('gc'); // nocommit
gc();

Notes:

This method should be used with care. Changing settings after the VM has started may result in unpredictable behavior, including crashes and data loss; or it may simply do nothing.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文