Run:
- node memory-leak.js
- node node fixed-memory-leak.js
Output will be four heapdumps files with coresponding names. Heapdumps can be inspected via Chrome Devtools.
const heapdump = require('heapdump'); | |
const uncached = require('./require-uncached-patch.js'); | |
let i; | |
for (i = 0; i < 100000; i++) { | |
require('./module.js')(); | |
} | |
heapdump.writeSnapshot('./FixedMemoryLeakBefore-' + Date.now() + '.heapsnapshot'); | |
for (i=0; i < 100000; i++) { | |
uncached('./module.js')(); | |
} | |
heapdump.writeSnapshot('./FixedMemoryLeakAfter-' + Date.now() + '.heapsnapshot'); |
const heapdump = require('heapdump'); | |
const uncached = require('require-uncached'); | |
let i; | |
for (i = 0; i < 100000; i++) { | |
require('./module.js')(); | |
} | |
heapdump.writeSnapshot('./MemoryLeakBefore-' + Date.now() + '.heapsnapshot'); | |
for (i=0; i < 100000; i++) { | |
uncached('./module.js')(); | |
} | |
heapdump.writeSnapshot('./MemoryLeakAfter-' + Date.now() + '.heapsnapshot'); |
module.exports = () => {}; |
{ | |
"name": "require-leak", | |
"version": "1.0.0", | |
"description": "", | |
"main": "index.js", | |
"scripts": { | |
"test": "echo \"Error: no test specified\" && exit 1" | |
}, | |
"keywords": [], | |
"author": "", | |
"license": "ISC", | |
"dependencies": { | |
"heapdump": "~0.3.7", | |
"require-uncached": "~1.0.2" | |
} | |
} |
'use strict'; | |
var path = require('path'); | |
var resolveFrom = require('resolve-from'); | |
var callerPath = require('caller-path'); | |
module.exports = function (moduleId) { | |
if (typeof moduleId !== 'string') { | |
throw new TypeError('Expected a string'); | |
} | |
var filePath = resolveFrom(path.dirname(callerPath()), moduleId); | |
// delete itself from module parent | |
if (require.cache[filePath] && require.cache[filePath].parent) { | |
var i = require.cache[filePath].parent.children.length; | |
while (i--) { | |
if (require.cache[filePath].parent.children[i].id === filePath) { | |
require.cache[filePath].parent.children.splice(i, 1); | |
} | |
} | |
} | |
// delete module from cache | |
delete require.cache[filePath]; | |
// return fresh module | |
return require(filePath); | |
}; |