Socket io emit message to client from express controller method
I know that usually you will have to app.js
create a socket server and pass that instance 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 is supposed to give progress to any client that happens to be listening, but that method can be executed from many different routes and other controllers, and I really don't want to pass the link socket
around all these other parts of the application.
Is there a better way to do this?
I was thinking something like a helper module socketio
. The module app.js
transmits a link to io
which you can get 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 when you need it in the application.
var io = require('./helpers/socketio').get();
io.emit('message', {a:1, b:2});
Is there a cleaner way to do this? Obviously it can return null, which you will need to check. It just doesn't feel right.
source to share