为什么response.write似乎在Node.js中阻止了我的浏览器? [英] Why does response.write appear to block my browser in Node.js?

查看:85
本文介绍了为什么response.write似乎在Node.js中阻止了我的浏览器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试按照此处的教程进行操作:

I'm trying to follow the tutorial here:

http://nodetuts.com/tutorials/2-webtail-nodejs-child-processes-and-http-chunked-encoding.html#video

以下代码有效

var http = require('http');
var spawn = require('child_process').spawn;

http.createServer(
function (request, response) {
    response.writeHead(200, {
        'Content-Type':'text/plain'
    });
    var tail_child = spawn('tail', ['-f', 'temp.txt']);

    request.connection.on('end', function () {
        tail_child.kill();
    });

    tail_child.stdout.on('data', function (data) {
        console.log(data.toString());
        response.end(data.toString());

    });

}).listen(9000);

但是,浏览器没有收到对temp.txt的更新.如果我更换

However the browser does not receive updates to temp.txt. If I replace

response.end(data.toString());

使用

response.write(data.toString());

它似乎被阻止,浏览器中没有任何内容.

It appears to block and nothing is rendered in the browser.

我希望浏览器按照教程的内容连续实时地实时显示文本文件中的任何内容

I would like the browser to continuously display any appends to the text file in real time as per the tutorial

推荐答案

您应该尝试使用curl来测试传输编码:分块.许多Web浏览器不会分块呈现内容,这可能是因为以这种方式呈现HTML并不是很有效.如果您将足够的数据放入响应中,最终浏览器可能会按照您的期望开始渲染它,但这不是我通常使用的解决方案.

You should try using curl instead to test out transfer-encoding: chunked. A lot of web browsers won't render the content in chunks, probably because it isn't really efficient to render HTML in that fashion. If you put enough data into the response eventually the browser may start rendering it as you'd expect though, but it isn't a solution I'd use normally.

如果您想以希望的方式将数据流式传输到Web浏览器,我会使用websockets或可能对流式页面进行的ajax调用,以呈现html格式,因为ajax调用应该触发每个块的事件.

If you want to stream data to a web browser in the way you're hoping, I'd use websockets or possibly an ajax call made to your streaming page that would render html as it comes, since an ajax call should fire events for each chunk.

这篇关于为什么response.write似乎在Node.js中阻止了我的浏览器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆