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

86
Visualizações
Sharing SocketIDs Across Node.js files

I have a MERN stack application, and I have an array that keeps track of the logged in users.

server/index.js
var connectedUsers = []

io.on('connection', (socket) => {
    socket.on('addUser', (userId) => {
        connectedUsers.push({userId, socket.id})
    })
})

I also have a POST request for creating a Post document.

server/controllers/post
export const createPost = async (req, res) => {
    const post = req.body;

    const newPostMessage = new PostMessage({ ...post, 
        creator: req.userId, createdAt: new Date().toISOString() })

    try {
        await newPostMessage.save();

        res.status(200).json(newPostMessage);
        awardBadges(req.userId)
    } catch (error) {
        res.status(50).json({ message: error.message });
    }
}

After creating a post document and sending it as a JSON, it will check to see if the user meets any requirements for a badge (similar to Stackoverflow badge)

export const awardBadges = async (userId) => {
   // Assign awards
   // Update user's awards field with the badges he received 
   // and mailbox field with that specifies which awards he received
}

If the user is connected and received a badge, it will emit a message so that the user will send a GET request to the database to get his mailbox field.

I know I can accomplish this by doing the following:

io.to(socket.id).emit("getMailbox");

But how can I access the socketId if it's in a different node.js file? Would I have to make the connectedUsers a global var?

about 4 years ago · Juan Pablo Isaza
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