Vijay
Vijay

Reputation: 159

Socket.io emit from nodejs controller, am i doing it right?

I'm new to nodejs and now in need of integrating socket.io into the app.

Basically its a e-commerce app where i need to show orders in admin screen automatically, so i'm using socket.io to emit the json for the latest order.

After more search i finally integrated with a simple solution of globally declaring the io variable and using it inside controllers.

One or more clients will connect to socket with a particular ID, and i'm emitting the output as below to that event.

server.js

var http = require('http').Server(app)
var io = require('socket.io')(http)
global._io = io

controller.js

exports.socketServer = (req,res) => {
    global._io.emit('groupid', "json_data")
})

So when new order is inserted from this module, i'm emitting the json to the users connected with the socket.

Is it fair enough!? What is the best practice and what are all the disadvantages of using the above code.

And i saw few posts stating to pass the io as attribute which i couldn't understand, so i really appreciate if anyone can explain me how to pass it.

Thanks

-Vijay

Upvotes: 1

Views: 1027

Answers (1)

mihai
mihai

Reputation: 38543

Using the global object is generally discouraged because of the naming conflicts it can cause. For example a module that you require may set global._io as well, sending your _io into the garbage collector.

However for small apps it's a perfectly viable solution, if you use a relatively small number of modules.

The recommended way to share a variable between modules is to put it into the exports object:

server.js

var http = require('http').Server(app)
var io = require('socket.io')(http)
exports.io = io;

controller.js

exports.socketServer = (req,res) => {
    require("server.js").io.emit('groupid', "json_data")
})

Upvotes: 4

Related Questions