inControl
inControl

Reputation: 2324

Nice way of splitting up Node.js code over multiple files

I currently have code similar to:

io.sockets.on('connection', function (socket) {
  socket.on('ping', function (data) {
    socket.emit("ping", data);
  });
});

I want to seperate:

socket.on('ping', function (data) {
   socket.emit("ping", data);
});

into a seperate file but that it is still able to use the socket variable, im using a lot of socket.on functions with in the 'connection' function and was wondering if there is anyway of splitting these sub function over multiple files. something like:

io.sockets.on('connection', function (socket) {
  require('otherFunctions.js');
});

Upvotes: 0

Views: 1067

Answers (1)

mpen
mpen

Reputation: 282825

This should work I think:

io.sockets.on('connection', require('otherFunctions.js').socketConnection);

And then in otherFunctions.js just export socketConnection:

exports.socketConnection = function(socket) {
    ...
}

Upvotes: 2

Related Questions