node.js中的module.parent有什么用? 我怎样才能参考require()ing模块?

我正在查看node.js模块文档,并注意到每个模块都有一个property- module.parent 。 我尝试过使用它,但是被模块caching模块烧毁。模块似乎只对那些首先需要()的模块而言,不pipe当前的上下文如何。

那么它的用法是什么? 有没有其他的方式可以让我参考当前的 require()ing模块? 现在我正在将模块封装在一个函数中,所以它被称为:

 require("mylibrary")(module) 

但是这似乎不是最佳的。

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

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

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

这是一个解决方法。 在完成加载之前,Node将模块添加到模块caching中。 这意味着一个模块可以在加载的时候从模块caching中删除自己 ! 然后每次模块require时,都会加载模块的新实例。

Magic.js

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

Module1.js

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

Module2.js

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

当然这样做的副作用是你的模块不再是单例,所以你必须在编写Magic.js时考虑到这一点。 如果您需要存储全局数据,则可以将其保存在不会从caching中删除自身的require()已编辑模块中。