From 520347c198cf2c168b1a8be6426a7575e64a3858 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 1d89698a7cfe24..52f2d059b5a1dc 100644 --- a/lib/internal/modules/cjs/loader.js +++ b/lib/internal/modules/cjs/loader.js @@ -877,6 +877,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); + } + } } } } 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': {