简体   繁体   English

Node.js客户端请求挂起

[英]Node.js client request hangs

I have a node.js process that uses a large number of client requests to pull information from a website. 我有一个node.js进程,它使用大量客户端请求从网站提取信息。 I am using the request package ( https://www.npmjs.com/package/request ) since, as it says: "It supports HTTPS and follows redirects by default." 我正在使用请求包( https://www.npmjs.com/package/request ),因为它说:“它支持HTTPS并默认遵循重定向。”

My problem is that after a certain period of time, the requests begin to hang. 我的问题是,在一段时间后,请求开始挂起。 I haven't been able to determine if this is because the server is returning an infinite data stream, or if something else is going on. 我无法确定这是否是因为服务器正在返回无限数据流,或者是否正在进行其他操作。 I've set the timeout, but after some number of successful requests, some of them eventually get stuck and never complete. 我设置了超时,但在一些成功的请求之后,其中一些最终会卡住并且永远不会完成。

var options = { url: 'some url', timeout: 60000 };
request(options, function (err, response, body) {
    // process
});

My questions are, can I shut down a connection after a certain amount of data is received using this library, and can I stop the request from hanging? 我的问题是,我可以在使用此库收到一定数量的数据后关闭连接吗?我可以阻止请求挂起吗? Do I need to use the http/https libraries and handle the redirects and protocol switching myself in order the get the kind of control I need? 我是否需要使用http / https库并自行处理重定向和协议切换以获得我需要的控制? If I do, is there a standardized practice for that? 如果我这样做,是否有标准化的做法?

Edit: Also, if I stop the process and restart it, they pick right back up and start working, so I don't think it is related to the server or the machine the code is running on. 编辑:此外,如果我停止进程并重新启动它,他们会选择正确的备份并开始工作,所以我认为它与服务器或代码运行的机器无关。

Note that in request(options, callback) , the callback will be fired when request is completed and there is no way to break the request. 请注意,在request(options, callback) ,当请求完成并且无法中断请求时,将触发回调。

You should listen on data event instead: 你应该听取data事件:

var request = require('request')

var stream = request(options);

var len = 0
stream.on('data', function(data) {
   // TODO process your data here

   // break stream if len > 1000
   len += Buffer.byteLength(data)
   if (len > 1000) {
      stream.abort()
   }
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM