How to use (socket.io)emit function outside of socket function - nodejs,express How to use (socket.io)emit function outside of socket function - nodejs,express express express

How to use (socket.io)emit function outside of socket function - nodejs,express


You almost had it:

it's io.emit('trigger','triggered');

And if you need to emit to a namespace you can do:

const namespace = io.of("name_of_your_namespace");namespace.emit('trigger','triggered');


You need to export your io first so that it can be reusable.

socket-setup.js

const socket = require("socket.io")let _io;const setIO = (server) => {    _io = socket(server, {        cors : {          origin : "*",          headers : {            "Access-Control-Allow-Origin" : "*"          }        }      })      return _io}const getIO = () => {    return _io}module.exports = {    getIO,    setIO}

Then in your app entry file (index.js), setup your io.

const app = express()const server = http.createServer(app)let io = setIO(server)io.on("connection", socket => { //Your job})

Then wherever, e.g. message.js you want to emit event. You can use io like this.

const onMessageRecieved = () => {    try {        getIO().emit("hello", "Bye")    } catch (error) {        console.log(error);    }}

That's it. Enjoy.