I want to call an io.emit('eventname') event of socket.io, when a custom event is triggered in another file in node.js. this happens in response to an HTTP request for a frontend app
moreover, I have created a common event emitter as simple importing and exporting the events was not firing, as expected, between files in node.js
commonEventEmitter.js
var events = require('events')
var em = new events.EventEmitter()
module.exports.commonEmitter = em;
This file receiles the HTTP request and triggers an event i.e 'newSOS, registered in socket.js file
sosRequest.js
const common = require('../utils/commonEventEmitter')
const commonEvent = common.commonEmitter
exports.createSOS = asyncHandler( async (req,res,next) => {
const { type , location } = req.body
Request = await SOS.findOne({type : type , createdBy: req.commuter[0].id ,
status:'Pending'})
commonEvent.emit('newSOS')
const request = await SOS.create({
type,
location,
createdBy,
})
res.status(200).json({
success:true,
request
})
In this file, 'newSOS' event is registered and is called many times as on an HTTP request is received.
socket.js
const io = require('socket.io')()
// const eventHandlers = require('./eventHandlers');
const common = require('../utils/commonEventEmitter')
const commonEvent = common.commonEmitter
io.on('connection' , (socket)=>{
commonEvent.on('newSOS' , ()=> {
console.log('running only once'.bgGreen)
io.emit('sos_admin' , "just do it")
})
}
module.exports = io
It's getting executed multiple times in 1 page. The pattern as follows:
If page is loaded first time it will be executed once. If page is loaded second time it will be executed twice. If page is loaded n times it will be executed n times.
and please also tell if my io.on('connection') is getting called multiple times?