Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

132
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda