简体   繁体   中英

Load a node.js module manually

Does anyone know how to use node's native "module" module (!) to load in a module manually from file as an alternative to using the normal require mechanism?

I know it's an odd request, but I need modules that declare their variables globally (to that module) and that are wrapped as new modules each time they are required, eg

var private;

module.exports = {
    setPrivate: function (value) {private = value} 
}

To elaborate, if you call require twice in separate places with the same path you get the same module back. I need to always get a new module so that when required in twice setPrivate can only affect its own variable;

Basically, I need to work out the mechanism that require() uses to create and return a module the first time it is called. Have played around with instantiating Module directly (as in https://github.com/joyent/node/blob/master/lib/module.js#L293 ), but no luck - the exports property is always an empty object.

Please guys no suggestions to just use a constructor... I appreciate I have an unusual use case.

You don't need to do anything so complicated.

Instead, you can simply delete it from the cache :

delete require.cache[module.id];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM