I'm creating a crawler to parse a game I have this function on the main file (crawler.js)
function kicked() {
try {
info.logged = false;
info.next_login = 0;
info.login_tries = 0;
report('Crawler disconnected from game, reconnecting.');
}
catch (error) {
report('Disconected() error => ' + error);
}
}
And i have
module.exports = { kicked: kicked };
and in another file (renew session) i have
var crawler = require('../../crawler');
but when i call the crawler.kicked()
i get undefined and if i use console.log(crawler);
it shows an empty object no errors nothing, just an empty object and i can't find why the file isn't exporting the function any help ?
The problem is that you have cyclic dependencies, which is what happens when A requires B, which requires A, etc. These are not always a problem. Node can handle cyclic dependencies. However, without a very good understanding of how Node modules are resolved, you are likely to run into problems (usually the empty-object problem).
Let's take a closer look at what's going on here:
crawler.js
), which begins to execute.crawler.js
requires session.js
.session.js
starts to execute its top-level code. Remember that crawler.js
has not finished executing its own top-level code.session.js
requires crawler.js
. But crawler.js
has nothing to export (yet). It hasn't yet reached the bottom of the file (it's still up at the top executing its require calls).So now we can see what's going on. The empty object is the default exports object. When you do module.exports = {...}
, you reassign the module's exports
property to a new object. But module.exports
has not yet been reassigned, for the reasons mentioned above.
The solution will be to rethink your code. I suggest trying to eliminate circular dependencies altogether; once you have a better grasp of how they work, you may want to use them from time to time. Your main file should probably not have any exports. Try putting your kicked
function in another file, and require that where needed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With