Question

Alright, so I've created a test project to show off this error. The error being that Node JS can't find my getStr function in my Another object.

This is the code:

test.js

var Another = require('./another.js');
var Other = require('./other.js');

var otherStr = Other.getStr();

console.log(otherStr);

other.js

var Another = require('./another.js');

var str = Another.getStr();

another.js

var Other = require('./other.js');

var str = "other String";

exports.getStr = function(){
    return str;
}

And this is my output:

C:\Users\Admin\Desktop\JS DEV\NODE DEV\server\test>node test.js

C:\Users\Admin\Desktop\JS DEV\NODE DEV\server\test\other.js:3
var str = Another.getStr();
                  ^
TypeError: Object #<Object> has no method 'getStr'
    at Object.<anonymous> (C:\Users\Admin\Desktop\JS DEV\NODE DEV\server\test\ot
her.js:3:19)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Object.<anonymous> (C:\Users\Admin\Desktop\JS DEV\NODE DEV\server\test\an
other.js:1:75)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)

C:\Users\Admin\Desktop\JS DEV\NODE DEV\server\test>

So how do I get Node JS to see Another's getStr function in Other?

Was it helpful?

Solution

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.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top