Streaming data with Node.js

后端 未结 3 1351
日久生厌
日久生厌 2020-12-04 08:51

I want to know if it is possible to stream data from the server to the client with Node.js. I want to post a single AJAX request to Node.js, then leave the connection open a

3条回答
  •  执笔经年
    2020-12-04 09:12

    You can also abort the infinite loop:

    app.get('/sse/events', function(req, res) {
        res.header('Content-Type', 'text/event-stream');
    
        var interval_id = setInterval(function() {
            res.write("some data");
        }, 50);
    
        req.socket.on('close', function() {
            clearInterval(interval_id);
        }); 
    }); 
    

    This is an example of expressjs. I believe that without expressjs will be something like.

提交回复
热议问题