Garbage collection can't keep up with Buffer creation and removal
<p>I have a method that runs every 2 seconds to capture a video stream to canvas and write it to file:</p>

<pre><code>  function capture(streamName, callback) {
    var buffer,
      dataURL,
      dataSplit,
      _ctx;

    _ctx = _canvas[streamName].getContext('2d');
    _ctx.drawImage(_video[streamName], 0, 0);
    dataURL = _canvas[streamName].toDataURL('image/png');
    dataSplit = dataURL.split(",")[1];
    buffer = new Buffer(dataSplit, 'base64');

    fs.writeFileSync(directory + streamName + '.png', buffer);
  }

  setInterval(function() {
    // Called from here
    captureState.capture(activeScreens[currentScreenIndex]);
    gameState.pollForState(processId, activeScreens[currentScreenIndex], function() {
      // do things...
    });
  }, 2000);
</code></pre>

<p>Assuming <code>_video[streamName]</code> exists as a running <code>&lt;video&gt;</code> and <code>_canvas[streamName]</code> exists as a <code>&lt;canvas&gt;</code>. The method works, it just causes a memory leak.</p>

<h3>The issue:</h3>

<p>Garbage collection can't keep up with the amount of memory the method uses, memory leak ensues.</p>

<p>I have narrowed it down to this line:</p>

<p><code>buffer = new Buffer(dataSplit, 'base64');</code></p>

<p>If I comment that out, there is some accumulation of memory (~100MB) but it drops back down every 30s or so.</p>

<h3>What I've tried:</h3>

<p>Some posts suggested <code>buffer = null;</code> to remove the reference and mark for garbage collection, but that hasn't changed anything.</p>

<p>Any suggestions?</p>

<p>Timeline: 
<a href="https://i.imgur.com/wH7yFjI.png" rel="nofollow">https://i.imgur.com/wH7yFjI.png</a>
<a href="https://i.imgur.com/ozFwuxY.png" rel="nofollow">https://i.imgur.com/ozFwuxY.png</a></p>

<p>Allocation Profile: 
<a href="https://www.dropbox.com/s/zfezp46um6kin7g/Heap-20160929T140250.heaptimeline?dl=0" rel="nofollow">https://www.dropbox.com/s/zfezp46um6kin7g/Heap-20160929T140250.heaptimeline?dl=0</a></p>

<p>Just to quantify. After about 30 minutes of run time it sits at 2 GB memory used. This is an Electron (chromium / desktop) app.</p>

<p><strong>SOLVED</strong>
Pre-allocating the buffer is what fixed it. This means that in addition to scoping <code>buffer</code> outside of the function, you need to reuse the created buffer with <code>buffer.write</code>. In order to keep proper headers, make sure that you use the <code>encoded</code> parameter of <code>buffer.write</code>.</p>