Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Module exports not working

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 ?

like image 835
user2942910 Avatar asked Feb 21 '16 10:02

user2942910


1 Answers

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:

  1. You start your main script (crawler.js), which begins to execute.
  2. crawler.js requires session.js.
  3. Now session.js starts to execute its top-level code. Remember that crawler.js has not finished executing its own top-level code.
  4. Now 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.

like image 138
McMath Avatar answered Nov 11 '22 20:11

McMath