I build a simple node.js / socket.io app. I need for emitting events a module, that can be accessible through other modules so I can send socket messages when there is for example a new database entry.
Something like this:
function sendWebsocketEvent (whereToSend, EventName, Payload) {
io.in(whereToSend).emit(EventName, Payload)
}
How can I handle that?
I've tried that:
-- app.js --
// Websockets
var http = require('http').createServer(app)
var io = require('socket.io')(http)
http.listen(3000, function () {
console.log('listening on Port *:3000')
})
require('./WebSockets/socketInit')(io)
-- socketInit.js --
module.exports = (ioInput) => {
const io = ioInput
return io
}
-- sendSockets.js --
const io = require('./socketInit')
module.exports = {
sendWebsocketEvent (whereToSend, EventName, Payload) {
io.in(whereToSend).emit(EventName, Payload)
}
}
And I tried to call this function at another module:
const sendSockets = require('../WebSockets/sendSockets')
.
.
.
sendSockets.sendWebsocketEvent('user', 'databaseUpdate', 'dataToSend')
.
.
.
But this doesn't work.
Is there an other way for getting this done?
- Chris