What you're dealing with here is a circular dependency. Node.js will let you load modules in a circular way but you need to design your code to account for it. Generally speaking, a circular dependency is a sign that the design is suffering from some flaw. In the code you've shown in the question, another
requires other
but does nothing with it. So the simplest fix would be to change another
so that it does not require other
.
If you have to keep the circular dependency for some reason or you want to experiment with circular dependencies for learning purposes, then this would be another possible fix:
var str = "other String";
exports.getStr = function(){
return str;
}
var Other = require('./other');
// Actually do something with Other down here.
By the time other
is required another
will at least have getStr
available. So this takes care of the immediate issue. Note however that your other
module does not export anything so your test.js
file will still fail at var otherStr = Other.getStr();
Probably you forgot to add this:
exports.getStr = function(){
return str;
}
(Note: I've modified the require
call so that it requires other
without the .js
suffix. Generally, you don't want to put suffixes in your require
calls. You want to put a module name which Node can resolve to a file, a package, or something else.)