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.

you can node documentation


Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -