4

This is what I've got so far, and I'm trying to find a solution so that:

  • The connection is always kept alive, so I can handle status updates
  • I can send a websocket message to a client with data from the POST request

ws api here

 router.post('/', function (req, res) {
// Need to send ws.send() with post data
})


wss.on('connection', function(ws) {
  ws.on('message', function(message) {
    console.log('r : %s', message);
  });
  // ws is only defined under this callback as an object of type ws
});

2 Answers 2

10

You can use event like this :

//Create an event
var event = require('events').EventEmitter();

router.post('/', function (req, res) {
   // fire an event
   event.emit('homePage')
})

wss.on('connection', function(ws) {
    ws.on('message', function(message) {
     console.log('r : %s', message);
    });

    // listen the event
    event.on('homePage', function(){
        ws.emit('someEvent');
    });
});
1
  • event is undefined when I try this Jun 11, 2018 at 19:50
1

I got an error:

TypeError: Cannot read property 'emit' of undefined

I think I could misunderstand or missing something that could be obvious for anyone else. The error comes when the emit call is requested:

router.post('/', function (req, res) {
   // fire an event
   event.emit('homePage') <----------- HERE
})

I'm adding at the beginning:

var event = require('events').EventEmitter();

UPDATE! I solved it changing the line where requires events by this 2:

var events = require('events');
var eventEmitter = new events.EventEmitter();

After that it's working.

1
  • I solved adding this at the begining... var events = require('events'); var eventEmitter = new events.EventEmitter(); May 24, 2018 at 1:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.