sse server sent events

13/04/2023

affiche 1 ligne par secondes.

et s'arrête après 10 secondes

    router.get('/property/gpt2/:id', async (req, res, next) => {
        res.setHeader('Cache-Control', 'no-cache');
        res.setHeader('Content-Type', 'text/event-stream');
        res.setHeader('Access-Control-Allow-Origin', '*');
        res.setHeader('Connection', 'keep-alive');
        res.flushHeaders();

        let counter = 0;
        const interValID = setInterval(() => {
            counter++;
            if (counter >= 10) {
                clearInterval(interValID);
                res.end();
                return;
            }
            res.write(`data: ${JSON.stringify({ num: counter })}\n\n`);
        }, 1000);

        // If client closes connection, stop sending events
        res.on('close', () => {
            console.log('client dropped me');
            clearInterval(interValID);
            res.end();
        });
    });

Raccourcis