Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
141
rated 0 times [  146] [ 5]  / answers: 1 / hits: 6830  / 8 Years ago, fri, april 8, 2016, 12:00:00

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.


More From » node.js

 Answers
8

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)


[#29591] Wednesday, April 6, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
iyannae

Total Points: 147
Total Questions: 88
Total Answers: 120

Location: Japan
Member since Sat, Jun 6, 2020
4 Years ago
;