Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
453 views
in Technique[技术] by (71.8m points)

node.js - Require returns an empty object

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

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

book.js

var Author = require('./author')
var Book = models.ActiveRecord.extend({
    schema : {
        belongsTo : {
            author : Author
        }
    }
})
module.exports = Book

author.js

var Book = require('./book')
var Author = models.ActiveRecord.extend({
    schema : {
        hasMany : {
            author : Book
        }
    }
})

module.exports = Author

The problem is that Author class does not seem to find the Book! It's just an empty Object. However, if I switch the exports in index.js, putting Book after Author - it works, but then the other model stops working.

I don't want to do any hacks to make it work.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...