NodeJS required module in module is always undefined

1.1k views Asked by At

I am pretty much new to backend-code. For now I try learning the architecture of a nodeJS-server.

My Problem for now is pretty simple I believe, but I can't run through -.-

server.js (main):

var io = require("socket.io"),
express = require("express"),
expressHbs = require('express3-handlebars'),
Player = require("./models/Player").Player,
Room = require("./models/Room").Room,
Game = require("./models/Game").Game,
dataSet = require('./data/data.json');
//...

Then I have 3 modules:

  1. Player
  2. Room
  3. Game

Each module is the same structure:

Player.js

// importing another module
var Room = require("./Room").Room;

if (!Player.players) {
    Player.players = {};
}

function Player(foo) {
    this.foo = foo;
    Player.players[foo] = this;
}

Player.getAllPlayersAsObject = function () {
    return Player.players;
};
// ...

Player.prototype.removePlayer = function () {
    if (Player.players.hasOwnProperty(this.id)) {
        delete Player.players[this.id];
    }
};
// ...

/**
 * node export
 * @type {Player}
 */
exports.Player = Player;

Room.js

var Player = require("./Player").Player;

if (!Room.rooms) {
    Room.rooms = {};
}

function Room(foo) {
    this.foo = foo
}

Room.getAllRoomsAsObject = function () {
    return Room.rooms;
};

Room.prototype.toString = function () {
    return JSON.stringify(this);
};

/**
 * node export
 * @type {Room}
 */
exports.Room = Room;

My main problem is, that I can use Room, Player, Game from server.js - constructor, prototype and all other functions normally.

In Player.js I can use the imported Room-module normally, too!

Room.js tells me:

path/path/path/gameserver/models/Room.js:222
var currentPlayer = Player.getPlayer(this.players[player].id);
                           ^
TypeError: Cannot read property 'getPlayer' of undefined

I am going crazy. What am I doing wrong? When I do a console.log (debug) of that variable "Player" at the top of the file, I am always getting undefined.

I walked around on google and here at stackoverflow, not finding any solution for my problem.

Thx and best regards,

Michael

1

There are 1 answers

0
knolleary On

You have a cyclic dependency between your modules.

You start by requiring Player. The first thing it does is require Room. Room then requires Player. At this point, Player has not yet completed its loading. Node prevents an infinite loop occurring by returning an incomplete version of Player. At this point, all bets are off as to what will happen.

You need to structure your modules to avoid this direct loop.

Background information of cyclic dependencies here: https://nodejs.org/api/modules.html#modules_cycles