如何使用管道控制node.js中的http流的流量

时间:2022-03-15 18:56:26

As Node.js developer knows, node can pipe the stream flow to another resource like http response.

正如Node.js开发人员所知,node可以将流流传输到另一个资源,如http响应。

Solution #1

http.createServer(function (req, res) {
   stream = fs.createReadStream(filename);
   stream.pipe(res);
});

Solution #2

There is another way to control flow of streaming and buffer response without piping

还有另一种方法可以在没有管道的情况下控制流和缓冲响应的流量

http.createServer(function (req, res) {

    stream = fs.createReadStream(filename);

    stream.on('data', function(data) {
        if (res.write(data) == false){ 
             stream.pause();
        }
    });

    stream.on('end', function(data) {
        res.end();
    });

    res.on('drain', function(data) {
        stream.resume();
    });


});

Is solution #2 better than #1 ?

I think It's better because we can control the flow of stream to http response. when response buffer is full and stream can't write data, stream will pause and when response become drain stream will resume

我认为这更好,因为我们可以控制流到http响应的流程。当响应缓冲区已满且流无法写入数据时,流将暂停,当响应变为耗尽时,流将恢复

My Problem

When I'm using the solution #2 my node application going to halt station and not response to other clients. this mean it only service to one client at a time ! I think this problem will occurs because node waiting to send res.end() to client and end the response. but I don't understand how to solve this issue.

当我使用解决方案#2时,我的节点应用程序将暂停站点而不响应其他客户端。这意味着它一次只能为一个客户服务!我认为会出现此问题,因为节点等待将res.end()发送到客户端并结束响应。但我不明白如何解决这个问题。

If this solution is absolutely wrong and I just need to use stream.pipe() please show me how can I control the flow of piping with resume and pause functions

如果这个解决方案是绝对错误的,我只需要使用stream.pipe(),请告诉我如何通过恢复和暂停功能控制管道流量

1 个解决方案

#1


2  

Solution #1 is basically equivalent to #2, except it's shorter code and you don't have to worry about the backpressure details.

解决方案#1基本上等同于#2,除了它的代码更短,您不必担心背压细节。

If your server is blocking other clients while writing the data, there's something wrong elsewhere.

如果您的服务器在写入数据时阻止其他客户端,则其他地方出现问题。

#1


2  

Solution #1 is basically equivalent to #2, except it's shorter code and you don't have to worry about the backpressure details.

解决方案#1基本上等同于#2,除了它的代码更短,您不必担心背压细节。

If your server is blocking other clients while writing the data, there's something wrong elsewhere.

如果您的服务器在写入数据时阻止其他客户端,则其他地方出现问题。