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

岁酱吖の 提交于 2019-11-29 01:33:24

问题


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

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

require("mylibrary")(module)

but that seems sub-optimal.


回答1:


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.




回答2:


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 itself from the module cache while it's loading! Then every time the module is require'd a new instance of the module is loaded.

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');

Of course the side-effect of this is that your module is no longer a singleton, so you have to code Magic.js with 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.



来源:https://stackoverflow.com/questions/13651945/what-is-the-use-of-module-parent-in-node-js-how-can-i-refer-to-the-requireing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!