122

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 ?

2
  • How are you loading these files? If you need to load a huge file, you must use the Stream approach and you can process the file while still reading. Have you consider it? Commented Oct 5, 2017 at 12:39
  • @well That was 3 years ago. I'm working on some other project now and can't remember much about it. Commented Oct 8, 2017 at 4:12

2 Answers 2

205

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.');
}
Sign up to request clarification or add additional context in comments.

13 Comments

Where the docs for "--expose-gc"? I am not find any docs in nodejs.org.
@pea3nut it's a option of the V8 runtime, which node uses. This and other options can be listed with node --v8-options
You have to pass true to the function for full GC otherwise it will just do a minor GC
FWIW, passing true (these days, at least) effects a minor collection: github.com/nodejs/node/blob/…
When would the catch block run? If --expose-gc is missing then global.gc will just be undefined
|
17

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.

1 Comment

Thanks, worked like a charm. Really helpful when writing unit tests that are run by IDE and you don't have control over node arguments.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.