How to detect v8 heap usage is close to limit in Node.js
<p>Now I use:</p>

<pre><code>const v8 = require('v8');

let heap = v8.getHeapStatistics();
let usage = 100 / heap.heap_size_limit * heap.used_heap_size;

if (usage &gt; 90) {
    console.log(`V8 heap usage close to the limit (${usage.toFixed()}%)`);
} else if (usage &gt; 95) {
    console.log(`V8 heap usage very close to the limit (${usage.toFixed()}%)`);
}
</code></pre>

<p>This solution not properly work.</p>

<p>When I try this command: node --max-old-space-size=100 index.js
My process down by unable allocate memory, when my script calculate ~56%</p>

<pre><code>getHeapStatistics().heap_size_limit is 178 MB
getHeapStatistics().used_heap_size is ~95 MB
</code></pre>

<p>How to detect situation more exactly, when we can get out of memory error?</p>