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

后端 未结 2 904
感情败类
感情败类 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:48

    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.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题