Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

118
Visualizações
eventemitter.on is getting registered and fired mutiple times in when using with sockets.io

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?

about 4 years ago · Santiago Gelvez
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda