在NodeJS结束之前关闭Http响应流 [英] Closing Http response stream in NodeJS before it ends

查看:822
本文介绍了在NodeJS结束之前关闭Http响应流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用nodejs中的请求模块发出请求,而我正在使用流式响应。此响应流通过管道传输到csv解析器并将记录填充到阵列上。一旦我得到预设的记录数,我想结束csv解析并关闭响应流。如何正确清理响应流。这是伪代码

I am using requests module in nodejs to make a request and I am streaming response I got. This response stream is piped to csv parser and populating records onto an array. Once I get a preset count of records, I want to end csv parsing and close the response stream. How do I properly cleanup response stream. Here is the pseudo code

var stream = request.get(url);
stream.pipe(csvParser);
var count = 15;
csvParser.on("readable",function(){
    while(record = csvParser.read()){
        if(records.length<count){
            records.push(record);
        } else {
            csvParser.end();
            //stream.close();
            //stream.unpipe();
            // stream.destroy();
        }
    }
});

csvParser.on("error",function(err){
    console.log("Error",err.message);
})

csvParser.on("finish",function(){
    //console.log("records",records);
    console.log("done");
})  

当我尝试使用stream.close()时,它说的是未定义的方法。什么是清理它的正确方法..?

when I try stream.close() , it's saying undefined method. What's the correct way of cleaning it up..?

推荐答案

可读流没有 close 方法。 关闭方法是老黑客仅关闭 fs 读取流(我不知道它是否仍在工作)

There is no close method for readable stream. close method is old hack to close only fs read stream (I do not know if it's still working)

此外,在可读流中没有方法 destroy

Also there is no method destroy in readable stream.

我担心在结束之前没有方法可以结束流。

I'm afraid there is no method to end stream before it ends.

你可以停止从流中读取。在你的情况下,流工作在流动模式,因此这个方法 csvParser.read()何时被调用,是对下一部分数据。如果你停止调用 csvParser.read()那么这个事件 csvParser.on(readable,function(){停止了开火。

You can stop reading from stream. In your case stream work in flowing mode, therefore this method csvParser.read() when is called, is requests for next parts of data. If you stop calling csvParser.read() then this event csvParser.on("readable",function(){ stopped to fire.

有一些很好的对话 https://groups.google.com/forum/#!msg/nodejs/eGukJUQrOBY/URD8I7tNxRUJ

这篇关于在NodeJS结束之前关闭Http响应流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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