node-mongo-demo

node.js and mongodb demo

git clone https://9o.is/git/node-mongo-demo.git

event-stream.js

(602B)


      1 class EventStream {
      2     #request;
      3     #response;
      4 
      5     constructor(request, response) {
      6         this.#request = request;
      7         this.#response = response;
      8 
      9         this.#response.writeHead(200, {
     10             'Content-Type': 'text/event-stream',
     11             'Connection': 'keep-alive',
     12             'Cache-Control': 'no-cache'
     13         });
     14     }
     15 
     16     writeJson(data) {
     17         this.#response.write('data: ' + JSON.stringify(data) + '\n\n');
     18     }
     19 
     20     close() {
     21         this.#response.end();
     22     }
     23 
     24     onClose(callback) {
     25         this.#request.on('close', callback);
     26     }
     27 }
     28 
     29 export default EventStream;