node.js node.js中module.parent有什么用?如何引用 require()ing 模块?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13651945/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:44:25  来源:igfitidea点击:

What is the use of module.parent in node.js? How can I refer to the require()ing module?

node.jsnode-modules

提问by Alastair

I was looking in the node.js moduledocumentation, and noticed that each module has a property- module.parent. I tried to use it, but got burnt by the module caching- module.parentonly ever seems to the module that first require()'d it, irrespective of current context.

我正在查看node.js 模块文档,并注意到每个模块都有一个属性 - module.parent。我尝试使用它,但被模块缓存烧毁了 -无论当前上下文如何,module.parent似乎只有首先需要()的模块才会使用它。

So what is the usage of it? Is there any other way for me to get a reference to the currentrequire()ing module? Right now I'm wrapping the module in a function, so that it is called like:

那么它的用途是什么呢?有没有其他方法可以让我获得对当前require()ing 模块的引用?现在我将模块包装在一个函数中,因此它的调用方式如下:

require("mylibrary")(module)

but that seems sub-optimal.

但这似乎不是最佳选择。

回答by Jonathan Lonowski

The "parent" is the module that caused the script to be interpreted (and cached), if any:

“父”是导致脚本被解释(和缓存)的模块,如果有的话:

// $ node foo.js
console.log(module.parent); // `null`
// require('./foo')
console.log(module.parent); // `{ ... }`

What you're expecting is the "caller," which Node doesn't retain for you. For that, you'll need the exported function you're currently using to be a closure for the value.

您期望的是“调用者”,Node 不会为您保留它。为此,您需要将当前使用的导出函数作为该值的闭包。

回答by Roy Paterson

There is a workaround for this. Node adds a module to the module cache before it finishes loading it. This means that a module can delete itselffrom the module cache while it's loading! Then every time the module is require'd a new instance of the module is loaded.

有一个解决方法。Node 在完成加载之前将模块添加到模块缓存中。这意味着模块可以在加载时从模块缓存中删除自己!然后每次模块require'da模块的新实例被加载。

Magic.js

魔术师

console.log('Required by ' + module.parent.filename);
delete require.cache[__filename];

Module1.js

模块1.js

//prints "Required by Module1.js"
require('./Magic');

Module2.js

模块2.js

//prints "Required by Module2.js"
require('./Magic');

Of course the side-effect of this is that your module is no longer a singleton, so you have to code Magic.jswith that in mind. If you need to store global data you can always keep it in a require()'ed module that doesn't delete itself from the cache.

当然,这样做的副作用是您的模块不再是单例,因此您必须在编写代码Magic.js时考虑到这一点。如果您需要存储全局数据,您可以始终将其保存在一个 require() 的模块中,该模块不会从缓存中删除自身。