nodejs express – 大块在res.on('data')中logging两次

我在nodeJS中遇到了一个问题,就像我看到的那样依赖于asynchronous,但是我无法处理它,而且我没有find解决具体问题的解决scheme。

我目前正在实现一个服务器每隔x秒轮询来自另一个服务器的数据。 然后,我使用外部服务器响应的数据块,这是一个JSONstring,接收必要的实时数据,然后parsing并保存到我的mongoDB。 问题是这个块有时会很长,因为服务器有时会传输很多行。

因此,有时我的工具已经工作,只要块不是太大,但有时它不。 logging块后,我注意到在这些情况下,块被logging两次。

例如,如果res.data看起来像这样:[1,“123”] [9,“234”](实际上它当然要大得多)我logging:

大块:[1,“123块”] [9,“234”]

这破坏了我的var response ,然后是response: "][9,"234"] 。这里是代码的重要部分:

 function pollUra() { var response = ''; var deferred = Q.defer(); // Send a request to URAv2 var req = http.request(options, function (res) { res.setEncoding('utf-8'); res.on('data', function (chunk) { // We need to set response to null here, because if there is too many data in the chunk, // the response concatenates chunk after chunk, while chunk is concatenated by its seperate parts. // chunk1 -> chunk1+chunk2 -> chunk1+chunk2+chunk3 // response = chunk1 -> chunk1+chunk1+chunk2 -> chunk1+chunk1+chunk2+chunk1+chunk2+chunk3... console.log('chunk: '+chunk); response = ''; response += chunk; }); res.on('end', function () { var parsedResponseArray = parser.parseQuery(response); ... } 

我认为评论中描述的灵魂解决了这个问题,因为它似乎是最有效的工作,但是现在看起来好像只有运气才能使这个块没有足够长时间的失败。

我希望在完全发送后才能捕获块,但是我不知何故找不到解决scheme,因为我认为res.on('end')是在数据块完全发送完之后调用的。

我错过了什么?

提前致谢!

删除行response = ''; 在你的res.on('data'...

否则代码看起来不错,问题是你重新初始化responsevariables。 因此,每次新到达时,先前保存的数据块都将被删除。


引用你:

例如,如果res.data看起来像这样:[1,“123”] [9,“234”](实际上它当然要大得多)我logging:

大块:[1,“123块”] [9,“234”]

请注意,块1 +块2 = [1,“123”] [9,“234”]

所以,代码必须是你所拥有的,但是不需要重置responsevariables:

 // Send a request to URAv2 var req = http.request(options, function (res) { res.setEncoding('utf-8'); response = ''; // Reset variable in case it is not empty res.on('data', function (chunk) { // We need to set response to null here, because if there is too many data in the chunk, // the response concatenates chunk after chunk, while chunk is concatenated by its seperate parts. // chunk1 -> chunk1+chunk2 -> chunk1+chunk2+chunk3 // response = chunk1 -> chunk1+chunk1+chunk2 -> chunk1+chunk1+chunk2+chunk1+chunk2+chunk3... console.log('chunk: '+chunk); response += chunk; }); res.on('end', function () { var parsedResponseArray = parser.parseQuery(response); ... }