4

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);
1
  • 1
    If you're going to pass the server object into the require statement like that, socketEvents.js should export a function. Commented Dec 16, 2015 at 0:13

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

9 Comments

This looks like what I am looking for and includes the server.js declarations so I'll mark this as the answer if it works...testing now...thanks.
Copied this into my project, node.js command prompt still shows 'server' is not defined exception on line 1 of socketEvents.js which is now 'function sockets(server) {', and I added the code you suggested to server.js also.
Works for me. Try this example: Server.js: var server = require('http'), sockets = require('./socketEvents'); sockets(server); socketEvents.js: function sockets(server) { console.log("Hello"); console.log(server); } module.exports = sockets;
Make sure you have the right path to sockeEvents.js file when you require it. In my example both files are in the same directory.
Ok 1 second, trying again. I am using a relative path but I know it's correct. I'll even try putting it in the same folder as server.js to be positive. 1 moment
|
2

Wrap it up in a function that you should export.

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

    io.... //rest goes here
}

module.exports = wrap;

1 Comment

After wrapping socketEvents.js in a function, and setting module.exports to this function, I am still seeing the same error in my node.js console, server is not defined on line 1 of socketEvents.js

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.