How to request the Garbage Collector in node.js to

2019-01-11 02:39发布

问题:

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 ?

回答1:

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.');
}


回答2:

Node allows us to manually trigger Garbage Collection. This can be accomplished by running Node with --expose-gc flag (i.e. node --expose-gc index.js).
Once node is running in that mode, you can programmatically trigger a Garbage Collection at any time by calling global.gc() from your program.

ex - //Force garbage collection every time this function is called

try {
  global.gc();
} catch (e) {
  console.log("You must run program with 'node --expose-gc index.js' or 'npm start'");
  process.exit();
}


回答3:

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.