From fe1bda9aeb9a54496b02c14889e8a85a962374c8 Mon Sep 17 00:00:00 2001 From: Qinhui Chen Date: Tue, 14 Apr 2020 10:58:01 +0800 Subject: [PATCH] module: fix memory leak when require error occurs Delete useless module in parent module: parent.children array when error occurs, so that it can be garbage collected. Fixes: https://github.com/nodejs/node/issues/32836 PR-URL: https://github.com/nodejs/node/pull/32837 Reviewed-By: Ben Noordhuis Reviewed-By: Andrey Pechkurov --- lib/internal/modules/cjs/loader.js | 7 +++++++ test/sequential/test-module-loading.js | 3 --- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/lib/internal/modules/cjs/loader.js b/lib/internal/modules/cjs/loader.js index 96aa4e2ebfc1aa..9db2b1e6c1c317 100644 --- a/lib/internal/modules/cjs/loader.js +++ b/lib/internal/modules/cjs/loader.js @@ -928,6 +928,13 @@ Module._load = function(request, parent, isMain) { delete Module._cache[filename]; if (parent !== undefined) { delete relativeResolveCache[relResolveCacheIdentifier]; + const children = parent && parent.children; + if (ArrayIsArray(children)) { + const index = children.indexOf(module); + if (index !== -1) { + children.splice(index, 1); + } + } } } else if (module.exports && ObjectGetPrototypeOf(module.exports) === diff --git a/test/sequential/test-module-loading.js b/test/sequential/test-module-loading.js index 2e55eb29369fcd..2a5cb5edd07f57 100644 --- a/test/sequential/test-module-loading.js +++ b/test/sequential/test-module-loading.js @@ -302,17 +302,14 @@ assert.throws( } }, 'fixtures/path.js': {}, - 'fixtures/throws_error.js': {}, 'fixtures/registerExt.test': {}, 'fixtures/registerExt.hello.world': {}, 'fixtures/registerExt2.test': {}, 'fixtures/module-load-order/file1': {}, 'fixtures/module-load-order/file2.js': {}, - 'fixtures/module-load-order/file3.node': {}, 'fixtures/module-load-order/file4.reg': {}, 'fixtures/module-load-order/file5.reg2': {}, 'fixtures/module-load-order/file6/index.js': {}, - 'fixtures/module-load-order/file7/index.node': {}, 'fixtures/module-load-order/file8/index.reg': {}, 'fixtures/module-load-order/file9/index.reg2': {}, 'fixtures/module-require/parent/index.js': {