Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to subscribe to eventstream - serverside

I have a url that return text/event-stream data so I am trying to connect and print everything I find:

var url = "..."
var source = new EventSource(url);

source.addEventListener('message', function(e) { 
    console.log(e.data);
}, false);

source.addEventListener('open', function(e) { }, false);

source.addEventListener('error', function(e) {
    if (e.readyState == EventSource.CLOSED) {  }
}, false);

unfortunately this doesn't work serverside. can I connect this way?

$ node app.js

app.js:2
var source = new EventSource(url);
                 ^

ReferenceError: EventSource is not defined
    at Object.<anonymous> (app.js:2:18)
    at Module._compile (module.js:409:26)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Function.Module.runMain (module.js:441:10)
    at startup (node.js:139:18)
    at node.js:968:3
like image 765
john mangual Avatar asked Nov 30 '25 04:11

john mangual


1 Answers

It seems you forgot on server side :

var EventSource = require("eventsource");
like image 199
Bertrand Martel Avatar answered Dec 02 '25 17:12

Bertrand Martel