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

后端 未结 2 927
感情败类
感情败类 2020-12-09 01:40

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 ca

2条回答
  •  误落风尘
    2020-12-09 01:59

    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.

提交回复
热议问题