Ad

Node.js Passing Object From Server.js To External Modules?

- 1 answer

I have these declarations at the top of my server.js file

var express = require('express'),
    app = express(),
    server = require('http').createServer(app),
    mongoose = require('mongoose'),
    bodyParser = require('body-parser'),
    apiRouter = require('./app/routes/api.js'),
    socketEvents = require('./app/modules/socketEvents.js')(server);

So I am trying to pass the 'server' var to my socketEvents module, the above method doesn't seem to be working. It throws an error in my Node.JS console that 'server' is not defined on line 1 of socketEvents.js, which I'll post below.

socketEvents.js

var io = require('socket.io')(server),
    matchMakingQueue = [];

io.on('connection', function(socket) {

    socket.on('joinMatchMaking', function(data) {
        //Every time a player joins the matchmaking queue, check if a game can be created.
        matchMakingQueue.push(data);
        var matchedPlayers = [];
        for (i = 0; i < matchMakingQueue.length; i++) {
            switch (data.gameType) {
                case '1v1':
                    matchedPlayers.push(matchMakingQueue[i].username);
                    if (matchedPlayers.length == 2) {
                        socket.emit('matchFound', {players: matchedPlayers});
                    } 
                    console.log('user joined 1v1 queue');
                case '2v2':
                    matchedPlayers.push(matchMakingQueue[i].username);
                    if (matchedPlayers.length == 4) {
                        socket.emit('matchFound', {players: matchedPlayers});
                    } 
                    console.log('user joined 2v2 queue');
            }
        }
        console.log(data.username + ' joined the ' + data.gameType + ' matchmaking queue');
        console.log('users in queue: ' + matchMakingQueue.length);
    });

    socket.on('leaveMatchMaking', function(username) {
        matchMakingQueue.splice(matchMakingQueue.indexOf(username), 1);
        console.log(username + ' left matchmaking queue.');
        console.log('users in queue: ' + matchMakingQueue.length);
    });

});

server.js

var express = require('express'),
    app = express(),
    server = require('http').createServer(app),
    mongoose = require('mongoose'),
    bodyParser = require('body-parser'),
    apiRouter = require('./app/routes/api.js'),
    socketEvents = require('./app/modules/socketEvents.js')(server);

//Clears Node Console.
process.stdout.write('\033c');
console.log('Server starting!');

app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json())

app.use('/api', apiRouter);
app.use(express.static('public'));

app.use('*', function(req, res, next) {
    //All requests return single page angular application.
    res.sendFile(__dirname + '/public/index.html');
});

mongoose.connect('localhost', 'triviaattack', function(err) {
    if (err) {
        console.log('An error occured when connecting to the MongoDB Database');
        throw err;
    }
});

server.listen(1337);
Ad

Answer

In socketEvents.js

function sockets(server) {
  var io = require('socket.io')(server),
      matchMakingQueue = [];

  // etc...
}

module.exports = sockets;

In server.js:

var sockets = require('./socketEvents'),
    express = require('express'),
    app = express(),
    server = require('http').createServer(app), 
    ...
    ...

sockets(server);

Basically you export the function from where you want to use them and then require those files in server.js.

Sample project:

server.js:

var sockets = require('./socketEvents')
server = require('http');

sockets(server);

socketEvents.js:

function sockets(server) {
  console.log("Hello");
  console.log(server);
}

module.exports = sockets;

Both files are in the same folder. To run: node server

Result: enter image description here

Ad
source: stackoverflow.com
Ad