diff --git a/lib/internal/modules/cjs/helpers.js b/lib/internal/modules/cjs/helpers.js index 3c49ab0a5d8..fea3fbcf48d 100644 --- a/lib/internal/modules/cjs/helpers.js +++ b/lib/internal/modules/cjs/helpers.js @@ -176,16 +176,19 @@ function addBuiltinLibsToObject(object, dummyModuleName) { get: () => { const lib = dummyModule.require(name); - // Disable the current getter/setter and set up a new - // non-enumerable property. - delete object[name]; - ObjectDefineProperty(object, name, { - __proto__: null, - get: () => lib, - set: setReal, - configurable: true, - enumerable: false - }); + try { + // Override the current getter/setter and set up a new + // non-enumerable property. + ObjectDefineProperty(object, name, { + __proto__: null, + get: () => lib, + set: setReal, + configurable: true, + enumerable: false, + }); + } catch { + // If the property is no longer configurable, ignore the error. + } return lib; }, diff --git a/test/parallel/test-cli-eval.js b/test/parallel/test-cli-eval.js index dcc2b8fcde3..b993dd47414 100644 --- a/test/parallel/test-cli-eval.js +++ b/test/parallel/test-cli-eval.js @@ -354,3 +354,12 @@ child.exec( common.mustSucceed((stdout) => { assert.match(stdout, /^number/); })); + +// Regression test for https://github.com/nodejs/node/issues/45336 +child.execFile(process.execPath, + ['-p', + 'Object.defineProperty(global, "fs", { configurable: false });' + + 'fs === require("node:fs")'], + common.mustSucceed((stdout) => { + assert.match(stdout, /^true/); + }));