Debug and analyze NodeJS Heap

Sometimes you run into issues with memory leaks or JavaScript heap out of memory errors within your NodeJS application and need to analyze it.
The Chrome DevTools ship with a useful tool for this where you can debug your application and inspect the Heap.
The following steps are needed to start inspecting your application:
- Start Node process in
inspectionmode. For this add the--inspectflag in your run command:
node --inspect index.js
For Typescript based projects you can use:
node --inspect -r ts-node/register ./index.ts
- Open Debug tools. Type in your Chrome browser:
chrome://inspect
- Click on
Open dedicated DevTools for Node - Choose the type which you want to see.
In the window which opened you can check the
CPU ProfilerorMemory Profiler- whichever is needed.
Addendum 1: Limiting space size
Wheny our application runs in a Kubernetes cluster or in an environment with limited space, you may want to simulate the memory limits there.
For this you can use the --max-old-space-size=512 flag. Which will limit the size of the Heap of the application.
Addendum 2: Differences between –inspect and –inspect-brk
In some documentations you’ll find the flag --inspect-brk instead of --inspect.
The difference is that the --inspect-brk code will break before your user code starts.