diff --git a/lib/internal/module.js b/lib/internal/module.js index aa1ffc01428bfa..a12af12f3e3d7e 100644 --- a/lib/internal/module.js +++ b/lib/internal/module.js @@ -59,21 +59,36 @@ exports.builtinLibs = ['assert', 'buffer', 'child_process', 'cluster', function addBuiltinLibsToObject(object) { // Make built-in modules available directly (loaded lazily). exports.builtinLibs.forEach((name) => { + // Goals of this mechanism are: + // - Lazy loading of built-in modules + // - Having all built-in modules available as non-enumerable properties + // - Allowing the user to re-assign these variables as if there were no + // pre-existing globals with the same name. + + const setReal = (val) => { + // Deleting the property before re-assigning it disables the + // getter/setter mechanism. + delete object[name]; + object[name] = val; + }; + Object.defineProperty(object, name, { get: () => { const lib = require(name); - // This implicitly invokes the setter, so that this getter is only - // invoked at most once and does not overwrite anything. - object[name] = lib; - return lib; - }, - // Allow the creation of other globals with this name. - set: (val) => { - // Deleting the property before re-assigning it disables the - // getter/setter mechanism. + + // Disable the current getter/setter and set up a new + // non-enumerable property. delete object[name]; - object[name] = val; + Object.defineProperty(object, name, { + get: () => lib, + set: setReal, + configurable: true, + enumerable: false + }); + + return lib; }, + set: setReal, configurable: true, enumerable: false });