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

混江龙づ霸主 提交于 2019-11-30 04:17:12

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.

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.

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