diff --git a/lib/internal/module.js b/lib/internal/module.js index 08d8f770c8d873..016a3437642cbe 100644 --- a/lib/internal/module.js +++ b/lib/internal/module.js @@ -83,43 +83,50 @@ const builtinLibs = [ 'string_decoder', 'tls', 'tty', 'url', 'util', 'v8', 'vm', 'zlib' ]; +// Make built-in modules available directly (loaded lazily). function addBuiltinLibsToObject(object) { - // Make built-in modules available directly (loaded lazily). - builtinLibs.forEach((name) => { + const configurable = true; + const enumerable = false; + + // Setter function that will be bound to some lib name + function setReal(libname, value) { + // Deleting the property before re-assigning it disables the + // getter/setter mechanism. + delete object[libname]; + object[libname] = value; + } + + for (var n = 0, len = builtinLibs.length; n < len; n++) { // 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 libname = builtinLibs[n]; + const set = setReal.bind(null, libname); - 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, { + Object.defineProperty(object, libname, { get: () => { - const lib = require(name); + const lib = require(libname); - // Disable the current getter/setter and set up a new - // non-enumerable property. - delete object[name]; - Object.defineProperty(object, name, { + // Disable the current getter/setter + delete object[libname]; + + // Set up a new non-emumerable propery + Object.defineProperty(object, libname, { get: () => lib, - set: setReal, - configurable: true, - enumerable: false + set, + configurable, + enumerable }); return lib; }, - set: setReal, - configurable: true, - enumerable: false + set, + configurable, + enumerable }); - }); + } } module.exports = exports = {