From fdc65d97699212b4c967206e3bbe171fe10734f7 Mon Sep 17 00:00:00 2001 From: Antoine du Hamel Date: Wed, 6 Sep 2023 12:12:14 +0200 Subject: [PATCH] esm: fix loading of CJS modules from ESM PR-URL: https://github.com/nodejs/node/pull/49500 Fixes: https://github.com/nodejs/node/issues/49497 Reviewed-By: Stephen Belanger Reviewed-By: Benjamin Gruenbaum Reviewed-By: Jacob Smith --- lib/internal/modules/esm/translators.js | 3 ++- test/es-module/test-esm-recursive-cjs-dependencies.mjs | 7 +++++++ test/fixtures/recursive-a.cjs | 6 ++++++ test/fixtures/recursive-b.cjs | 3 +++ 4 files changed, 18 insertions(+), 1 deletion(-) create mode 100644 test/es-module/test-esm-recursive-cjs-dependencies.mjs create mode 100644 test/fixtures/recursive-a.cjs create mode 100644 test/fixtures/recursive-b.cjs diff --git a/lib/internal/modules/esm/translators.js b/lib/internal/modules/esm/translators.js index c0125cd84c3..80228e895fa 100644 --- a/lib/internal/modules/esm/translators.js +++ b/lib/internal/modules/esm/translators.js @@ -279,7 +279,8 @@ translators.set('commonjs', async function commonjsStrategy(url, source, // obtained by calling the monkey-patchable CJS loader. const cjsLoader = source == null ? (module, source, url, filename) => { try { - module.load(filename); + assert(module === CJSModule._cache[filename]); + CJSModule._load(filename); } catch (err) { enrichCJSError(err, source, url); throw err; diff --git a/test/es-module/test-esm-recursive-cjs-dependencies.mjs b/test/es-module/test-esm-recursive-cjs-dependencies.mjs new file mode 100644 index 00000000000..d75f0fae95d --- /dev/null +++ b/test/es-module/test-esm-recursive-cjs-dependencies.mjs @@ -0,0 +1,7 @@ +import '../common/index.mjs'; +import { strictEqual } from 'node:assert'; + +import '../fixtures/recursive-a.cjs'; + +strictEqual(global.counter, 1); +delete global.counter; diff --git a/test/fixtures/recursive-a.cjs b/test/fixtures/recursive-a.cjs new file mode 100644 index 00000000000..a60c0a635dd --- /dev/null +++ b/test/fixtures/recursive-a.cjs @@ -0,0 +1,6 @@ +'use strict'; + +global.counter ??= 0; +global.counter++; + +require('./recursive-b.cjs'); diff --git a/test/fixtures/recursive-b.cjs b/test/fixtures/recursive-b.cjs new file mode 100644 index 00000000000..e9f0b5d0701 --- /dev/null +++ b/test/fixtures/recursive-b.cjs @@ -0,0 +1,3 @@ +'use strict'; + +require('./recursive-a.cjs');