factor_za
factor_za

Reputation: 119

Express.js include socket events from another file?

I am new to express and find that my app.js is getting a bit crowded. Is there a way that I could take all of my socket events, put them in another file in a folder and include it within

io.sockets.on("connection", function(socket){
  //Require socket event file here
});

I attempted something along the lines of:

 require('./mysockets')(server);

and in the other file doing:

var io = require("socket.io");

// declare module constructor that is passed the http server to bind to
module.exports = function(server) {
     io.listen(server);
     //My code here
 };

Am I missing something in this instance? I have included a pastebin: http://pastebin.com/zvs8aMjN

This shows the error i am getting in console when I do the above.

EDIT:

Added my socket events to show how it is being used. I have confirmed all this code works when running it directly from my app.js, however the require seems to break it.

  console.log("Client connection, no username");

    // ===============================================
    // DISCONNECTION
    // ===============================================
    socket.on('disconnect', function(data) {
      // Allows us to track if a unknown user has disconnected or if a known user has dosconnected
      if(!socket.username) {
        console.log("Client disconnected before username");
      } else {
        console.log("Player " + socket.username + " disconnected");
        serverFunctions.lobbyCheck();
        // Removes only one user
        allUsers.splice(allUsers.indexOf(socket.username), 1);
      }

      // Calls update usernames function
      serverFunctions.updateUsernames();
    });

    // ===============================================
    // NEW PLAYER LOGIC
    // ===============================================

    // Player has connected
    // Checks if username is already been used
    socket.on("new user", function(data, callback){
      // If it exists return false, else add it to array of allUsers
      if (allUsers.indexOf(data) != -1) {
        callback(false);
      } else {
        callback(true);
        socket.username = data;
        allUsers.push(socket.username);
        // Tells all active users which users are active
        serverFunctions.updateUsernames();
        console.log("Player " + socket.username + " connected");

        serverFunctions.lobbyCheck();
        // Calls theplayer check in order to push through the player names client side
        serverFunctions.playerCheck();
      }
    });

    // ===============================================
    // Game Start Logic
    // ===============================================

    // ===============================================
    // CHAT LOGIC
    // ===============================================

    // Broadcasts a message
    socket.on("send message", function(data){
      io.sockets.emit("new message", {msg: data, user: socket.username});
    });
});

This happens above my socketconnection:

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index');
var users = require('./routes/users');

var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hjs');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

Upvotes: 3

Views: 2243

Answers (1)

Zohaib Ijaz
Zohaib Ijaz

Reputation: 22875

In app.js you are getting io object like this

var io = require('socket.io')(server);

Now you need to pass this io object to your sockets module so the code can add listners to this object.

In app.js replace

require('./mysockets')(server);

with

require('./mysockets')(io);

Because you have to pass io object, not the server obeject.

And in mysockets.js file

module.exports = function(io) {
    io.sockets.on("connection", function(socket){
          // Broadcasts a message
          socket.on("send message", function(data){
             io.sockets.emit("new message", {msg: data, user: socket.username});
          });

        // other listeners will go here.
    });
};

Upvotes: 5

Related Questions