2

I have two files (for example).

./database/user.js

module.exports = {
    getUniqueByID: function(params){
        doSomething();
        return anUserObject;
    }
};

./database/uperm.js

var dbUser = require('./user.js');
module.exports = {
    createNew: function(params){
        dbUser.getUniqueByID(uid);
        doSomethingElse();
    }
};

Function createNew() from uperm.js always throws an exception:

.../uperm.js:123
dbUser.getUniqueByID(uid);
TypeError: dbUser.getUniqueByID is not a function

But, if i change ./database/uperm.js to be:

module.exports = {
    createNew: function(params){
        require('./user.js').getUniqueByID(uid);
        doSomethingElse();
    }
};

Then getUniqueByID() from user.js is called by createNew() from uperm.js, without any exception.

But I don't whant to use require('./user.js') everywhere, instead of assigning it to dbUser variable.

What's wrong in case of using variable? Absolutely similar code in other files of my project seems to be ok.

cl3m
  • 2,791
  • 19
  • 21
Denis Golovkin
  • 106
  • 2
  • 11

1 Answers1

2

Since you have circular dependencies, try to set properties of the module.exports instead of directly overwriting it:

var functions = {
   getUniqueByID: xxx
};

for(var key in functions) {
    module.exports[key] = functions[key];
}

(From the idea provided in this answer)

Community
  • 1
  • 1
christophetd
  • 3,834
  • 20
  • 33
  • I've tryed var foos = { getUniqueByID: xxx }; module.exports = foos; ... But this does't help. Your solution works even if file1 depends on file1 and file2 and file 2 depends on file1 and file2 as well. Thank you again. – Denis Golovkin Apr 08 '16 at 22:52