简体   繁体   English

手动加载node.js模块

[英]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? 有谁知道如何使用节点的本机“模块”模块(!)从文件中手动加载模块,以替代使用常规的require机制?

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; 我需要始终获取一个新模块,以便在两次调用setPrivate时仅能影响其自身的变量;

Basically, I need to work out the mechanism that require() uses to create and return a module the first time it is called. 基本上,我需要弄清楚require()在首次调用模块时用于创建和返回模块的机制。 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. 已经直接实例化了Module(例如https://github.com/joyent/node/blob/master/lib/module.js#L293 ),但是没有运气-Exports属性始终是一个空对象。

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];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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