Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

127
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!