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)
}
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
- Please refer my recently added article on socket.io, this could help you: github./sarveshmahajan89/My-Chat-App – Sarvesh Mahajan Commented Jan 26, 2020 at 18:18
1 Answer
Reset to default 6Inside Server.js
const express = require('express');
const app = express();
const server = require('http').createServer(app)
const io = socket.listen(server);
global.io = io;
const port = process.env.PORT || 5500;
server.listen(port, () => console.log(`%s