最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

express - HTTPS streaming with Node.js - Stack Overflow

programmeradmin0浏览0评论

I am trying to emit chunks of data with a Node.js endpoint, the goal is to display it dynamically with curl. But when I use curl -X GET , nothing is displayed until everything is displayed all at once (I want the output to be dynamic, not just everything at the end). I also tried with a python flask streaming server and it works, so I guess the issue has something to do with Node.js.

Below my code :

app.get('/stream', (req, res) => {
    res.setHeader('Content-Type', 'text/plain; charset=utf-8');
    res.setHeader('Transfer-Encoding', 'chunked');
    
    const responseChunks = [
        "Hello,",
        "how are you",
        "...\n"
    ];

    let chunkIndex = 0;

    // Send data every 500ms
    const intervalId = setInterval(() => {
        if (chunkIndex < responseChunks.length) {
            res.write(responseChunks[chunkIndex]);
            chunkIndex++;
        } else {
            clearInterval(intervalId);
            res.end(); 
        }
    }, 500);

    req.on('close', () => {
        clearInterval(intervalId); 
        console.log('Stream stopped.');
    });
});

...

https.createServer(credentials, app).listen(443, '0.0.0.0', () => {
    console.log(`HTTPS Server is running on :443`);
});

I already checked How do I stream response in express?, but I got the same problem, the result in curl command is displayed at the end, I want the output to be dynamic.

发布评论

评论列表(0)

  1. 暂无评论