1

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
1

1 Answer 1

6

Inside 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 🚀 Server is listening on port ${port}`, chalk.green('✓')));

// socket io connection 
let interval;
io.on("connection", socket => {
    console.log("New client connected");
    if (interval) {
        clearInterval(interval);
    }
});

And emit where you want just like that

global.io.emit('EventName', data);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.