> For the complete documentation index, see [llms.txt](https://jen-hsuan-hsieh.gitbook.io/javascript-node-js/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jen-hsuan-hsieh.gitbook.io/javascript-node-js/chapter2-nodejs/23nodejs-debug-message/232allow-nodejs-perform-gc-collection.md).

# 2.3.2.Allow node.js perform GC collection

* 1.sudo npm install heapdump
* 2.加入：

  ```
  require('heapdump');
  var leakyData = [];
  var nonLeakyData = [];

  function generateHeapDumpAndStats(){
    //1. 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();
    }

    //2. Output Heap stats
    var heapUsed = process.memoryUsage().heapUsed;
    //console.log("Program is using " + heapUsed + " bytes of Heap.");
    debug("Program is using " + heapUsed + " bytes of Heap.");
    //3. Get Heap dump
    //process.kill(process.pid, 'SIGUSR2');
  }

  setInterval(generateHeapDumpAndStats, 2000);
  ```
* 3.在命令列中執行:

  ```
        node --expose-gc app.js
  ```
* 4.reference: <http://www.alexkras.com/simple-guide-to-finding-a-javascript-memory-leak-in-node-js/>
