如何在NodeJS中刷新任意大小的块

mar*_*ran 2 http flush chunks node.js

在Node Web服务器中,我想在特定点刷新HTML内容,如下所示:

  • 第一块: <html><head> ... </head>
  • 第二块: <body> ... </body>
  • 第3块: </html>

例如:

var http = require('http');

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});

  res.write('<html><head> ... </head>');                                           

  setTimeout(function() {                                                          
    res.write('<body> ... </body>');                                               

    setTimeout(function() {                                                        
      res.end('</html>');                                                          
    }, 2000);                                                                      

  }, 2000);

}).listen(8000);
Run Code Online (Sandbox Code Playgroud)

上面的代码<html><head> ... </head><body> ... </body></html>在一个块中响应~4s后,但是我注意到块应该> = 4096bytes才能立即刷新:

var http = require('http');

http.createServer(function (req, res) {                                            
  res.writeHead(200, {'Content-Type': 'text/plain'});                              

  res.write(Array(4097).join('*'));

  setTimeout(function() {                                                          
    res.write(Array(4097).join('#'));

    setTimeout(function() {                                                        
      res.end('done!');                                                            
    }, 2000);

  }, 2000);

}).listen(8000);
Run Code Online (Sandbox Code Playgroud)

上面代码的响应也需要大约4秒,但是会立即刷新块.我可以填充小块来填充至少4096字节,只是想知道是否还有另一种"非hacky"方式.

在PHP中,这可以通过flush()/ ob_flush()和禁用来实现output_buffering

FWIW,我正在构建一个Web服务器工具来试验几个HTML块输出配置,并在它们之间有一个给定的延迟,以便分析现代浏览器如何处理它并选择最佳配置.

谢谢

log*_*yth 5

这是一个半复制的问题.

答案是已经做了你想做的事情,只是浏览器没有解析并显示任何东西,直到它收到足够的数据来解析它.发送4097的块使浏览器能够解析部分文档,它不会推动Node以不同方式发送块.

curl如果将其置于非缓冲模式,则可以使用它进行测试.

curl -N localhost:8000
Run Code Online (Sandbox Code Playgroud)