node.js - Socket io emit message to client from express controller method -
i know have app.js
create socket server, , pass instance down router, in turn can pass controller methods. shown here (socket.io emit express controllers)
however, have controller method needs emit progress client happens listening, method can executed many different routes, , other controllers, , don't want have pass reference socket
around these other parts of app.
is there better way it?
i thinking socketio
helper module. app.js
module passes reference io
, can 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 need in app..
var io = require('./helpers/socketio').get(); io.emit('message', {a:1, b:2});
is there cleaner way this? return null, have check for. doesn't feel right....
modules cached after first time loaded.
actually, can verify socket.io @ helper/socketio.js
. although call require()
socketio.js
other files, node.js execute code on file 1 time.
Comments
Post a Comment