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

129
Visualizações
Websockets ws - Node & Express - export API

I got successfully my websocket up and running but I need to use the .send() method on my route.

I got my app split on several files. In this case I got:

app.js

//..some other code..

//Server

const server = http.createServer(app)
var port = process.env.PORT || 80;
const connection = server.listen(port, () => {
  console.log('Listening on ' + port);
});


const WebSocketServer = require("ws").Server;
const wss = new WebSocketServer({
  server
});

//Here I need to export the wss

module.exports.sengMsg = function (msg, callback) {
  return wss.on("connection", function (ws) {

    ws.send(msg, callback);


    ws.on("close", function () {
      console.log("websocket connection close")
    })
  })
};

api.js

//..some other code..

var sendMsg = require('../app').sendMsg;


router.get('/', (req, res) => {
    sendMsg('Hi I from default route', (err)=>{
       console.log("I got some error on ws");
    })
    res.send('Welcome to my API');

})

But in the end I come up with

TypeError: sendMsg is not a function

What is the recommended way to export the funcionality of my wss on my routes using this setup ?

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Try changing the code to,

var sendMsg = require('./app');

router.get('/', (req, res) => {
   sendMsg.sendMsg('Hi I from default route', (err)=>{
   console.log("I got some error on ws");
   })
   res.send('Welcome to my API');

})

or change the app.js module.exports to following,

module.exports = {
sendMessage :function (msg, callback) {
    return wss.on("connection", function (ws) {

        ws.send(msg, callback);


        ws.on("close", function () {
            console.log("websocket connection close")
        })
    })
}
}
about 4 years ago · Santiago Trujillo Relatório
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