nodejs require cause memory leak

Created on 1 Aug 2017  路  4Comments  路  Source: nodejs/node

  • Version: 4.3.1
  • Platform:window 64
  • Subsystem:


// test.js **************
var app
app=require('./test1')

setInterval(function() {
delete require.cache[require.resolve('./test1')]
app = require('./test1')
}, 2000)

setInterval(function() {
console.log('==================')
console.log(process.memoryUsage())
console.log('==================')
}, 500)

// test1.js **************

var arr = new Array(40 * 1024 * 1024)
module.exports = {
a: arr
}

Then ,i run the node with the follow command:

node --trace_gc test.js

In console, i get out of memory

image

memory module

Most helpful comment

this came up just recently, but can't find the ticket.

The leak is because the module is also cached in the module .parent.children; deleting it from require.cache is not sufficient. Need to

mod = require.cache[path];
delete require.cache[path];
ix = mod.parent.children.indexOf(mod);
if (ix >= 0) mod.parent.children.splice(ix, 1);

All 4 comments

this came up just recently, but can't find the ticket.

The leak is because the module is also cached in the module .parent.children; deleting it from require.cache is not sufficient. Need to

mod = require.cache[path];
delete require.cache[path];
ix = mod.parent.children.indexOf(mod);
if (ix >= 0) mod.parent.children.splice(ix, 1);

Duplicate of #8443, closing. Thanks for answering, @andrasq.

Thanks for answering

Even with the below added code as suggested by andrasq, there is memory leak.

mod = require.cache[path];
delete require.cache[path];
ix = mod.parent.children.indexOf(mod);
if (ix >= 0) mod.parent.children.splice(ix, 1);

Please see the below example:

while(true) {
  var file = './test1';
  require(file);


  var mod = require.cache[require.resolve(file)];
  if (mod) {
    var ix = mod.parent.children.indexOf(mod);
    if (ix >= 0) {
      mod.parent.children.splice(ix, 1);
    }
  }

  delete require.cache[require.resolve(file)];
}

The above code will leak memory over 1mb/sec. Any pointers on how to make the above code work to not leak memory are greatly appreciated.

Was this page helpful?
0 / 5 - 0 ratings