11

I'm trying to separate my socket.io code into a separate file (socket.js) from my main file (app.js). However, I need to define my io object in app.js, which is also used in my socket.js file.

Currently, I set io as a global variable so it is accessible from app.js (Global Variable in app.js accessible in routes?), but I understand this is bad practise. Is there a better way to do this (can injection work in this case, as I need to export a variable from the app.js to socket.js rather than the other way round)? Thank you!

app.js

var app = express(),
  server = require('http').createServer(app);

//KIV -> io is set as a global variable
io = require('socket.io').listen(server);
require('./socket');

socket.js

io.sockets.on('connection', function(socket) {
    //xxx
}
Community
  • 1
  • 1
Dan Tang
  • 1,273
  • 2
  • 20
  • 35

2 Answers2

19

One of the ways is by passing the object as argument to function (as already has been described in @Thomas' answer).

Other way is to create a new file say 'global.js'. put only those items in this file that you want to be global. e.g.

var Global = {
    io : { }
};    
module.exports = Global;

Now, in your app.js,

var app = express(),
    server = require('http').createServer(app), 
    global = require('./global.js');

global.io = require('socket.io').listen(server);
require('./socket');

And in your socket.js:

var global = require('./global.js');
global.io.sockets.on('connection', function(socket) {
    //xxx
}

Hope it helps...

jsist
  • 5,223
  • 3
  • 28
  • 43
  • One caveat with this: wouldn't this create a separate instance of `global.js` in each file that requires it? So if there is some state or data in `global.js` that you need to access in multiple modules, not just `socket.js`, then you this wouldn't work as the global object accessed in `socket.js` is not the same object accessed in your other child module.... – Alex Bowyer Jul 07 '18 at 11:44
  • 1
    @alexbfree it would not create separate instance of `Global` for each file it is required in. It will be same instance. – jsist Jul 14 '18 at 12:47
11

app.js

var app = express(),
  server = require('http').createServer(app),
  socket = require('./socket');

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

socket(io)

socket.js

module.exports = function (io) {
  io.sockets.on('connection', function(socket) {
    // Your code here

  });
}
Thomas Blobaum
  • 3,680
  • 1
  • 17
  • 16