Monday 1 May 2017

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 ?



via Korte

No comments:

Post a Comment