const readables = new Set(); function startServer() { // ··· server.get('/server-sent-events', async (request, reply) => { reply.type('text/event-stream').code(200); const readable = new SimpleReadable(); // Optional: send the current full status // The server closes the readable for us – if the connection is broken readable.addListener('close', () => { readables.delete(readable); }); // This is how we send incremental updates: readables.add(readable); return readable; // send to client }); // ··· } function sendIncrementalUpdate(date) { const data = { dateString: date.toISOString(), }; // Must not contain newlines (apart from those at the end)! const chunk = `data: ${JSON.stringify(data)}\n\n`; for (const readable of readables) { readable.push(chunk); } } //========== Helper class /** * Use `.push()` to add data chunks to instances of this class. */ class SimpleReadable extends stream.Readable { _read() { // do nothing } closeSimpleReadable() { this.push(null); } }