// Connecting to the server-side event stream
constevtSource=newEventSource("https://example.com/events");// Handling generic message events
evtSource.onmessage=event=>{console.log('got message: '+event.data);};
Server:
importexpressfrom'express';constapp=express();constPORT=process.env.PORT||3000;app.get('/events',(req,res)=>{res.writeHead(200,{'Content-Type':'text/event-stream','Cache-Control':'no-cache','Connection':'keep-alive',});constsendEvent=(data)=>{// all message lines must be prefixed with 'data: '
constformattedData=`data: ${JSON.stringify(data)}\n\n`;res.write(formattedData);};// Send an event every 2 seconds
constintervalId=setInterval(()=>{constmessage={time:newDate().toTimeString(),message:'Hello from the server!',};sendEvent(message);},2000);// Clean up when the connection is closed
req.on('close',()=>{clearInterval(intervalId);res.end();});});app.listen(PORT,()=>console.log(`Server running on http://localhost:${PORT}`));