I know that usually you would have app.js
create the socket server, and pass that instance down to your router, which in turn can pass it to controller methods. As shown here (Socket.io emit from Express controllers)
However, I have a controller method that needs to emit progress to any client who happens to be listening, but this method can be executed from many different routes, and other controllers, and I don't really want to have to pass a reference to socket
around all these other parts of the app.
Is there a better way to do it?
I was thinking something like a socketio
helper module. The app.js
module passes it a reference to io
, which can be retrieved later....
app.js
var io = require('socket.io').listen(server);
require('./helpers/socketio').set(io);
helpers/socketio.js
var io=null;
exports.set = function(socketio) {
io=socketio;
}
exports.get = function() {
return io;
}
Then whenever you need it in the app..
var io = require('./helpers/socketio').get();
io.emit('message', {a:1, b:2});
Is there a cleaner way to do this? Clearly it could return null, which you would have to check for. It just doesn't feel right....