Require returns an empty object

后端 未结 1 1963
走了就别回头了
走了就别回头了 2020-12-02 05:50

I have a folder, that has index.js and a couple of models (classes) index.js

module.exports = {
   Book : require(\'./book\'),
   Author : require(\'./author         


        
相关标签:
1条回答
  • 2020-12-02 06:09

    This is because you have a circular dependency. Node.js handles this in a very specific way:

    1. The first module loads and runs (in this case, book.js). It (book.js) will load and run the second module (author.js) when it (book.js) requires the other (author.js)

    2. When the second module (author.js) is loaded and run, it (author.js) requires the first module (book.js) but it (author.js) will receive a partially filled object - however many things were set on the exports in book.js before it required author.js will be in that object

    3. After book.js is completely run through, the object author.js got from require('./book') will be the full book.js module object

    For more info, here's the docs: http://nodejs.org/api/modules.html

    If its possible to dynamically add that schema to one of those ActiveRecord objects, that's one way to solve this. This is actually kind of a tricky situation. In fact, even without the module system, this would cause problems for you. If you put all this code in one file, how would you make it work?

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