由于我不能对this question的答案发表评论,所以我想在这里提供一些帮助。
我有完全相同的代码,但输出如下:
/**
* Created by Ramiro on 09/06/2015.
*/
// Load the http module to create an http server.
var http = require('http');
// Configure our HTTP server to respond with Hello World to all requests.
var server = http.createServer(function (request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
//console.log(dbHandler.GetDatabase());
var req = http.request('http://127.0.0.1:5984/_myUri', function(res) {
res.setEncoding('utf8');
var body = '';
// Streams2 API
res.on('readable', function () {
var chunk = this.read() || '';
body += chunk;
console.log('chunk: ' + Buffer.byteLength(chunk) + ' bytes');
});
res.on('end', function () {
console.log('body: ' + Buffer.byteLength(body) + ' bytes');
});
req.on('error', function(e) {
console.log("error" + e.message);
});
});
req.end();
response.end();
});
// Listen on port 8000, IP defaults to 127.0.0.1
server.listen(3000);有了这个输出:
chunk: 230 bytes
chunk: 0 bytes
body: 230 bytes
chunk: 230 bytes
chunk: 0 bytes
body: 230 bytes
chunk: 230 bytes
chunk: 0 bytes
body: 230 bytes这使我推断:
发布于 2015-06-10 02:04:03
每个通过的块都会抛出“可读”事件,有时还会包含一个偏离0。我相信在您的情况下会发生这种情况,而且由于您的console.log行得到的是聚合的"body“值,而不是单个的”块“,所以两次都可以看到230个。(返回230,然后返回0,但每次返回的总数为230)。要获得总数据,只需连接在“end”回调中调用的所有块。看看这能给你带来什么:
var req = http.request('http://127.0.0.1:5984/_myUri', function(res) {
res.setEncoding('utf8');
var body = '';
// Streams2 API
res.on('readable', function () {
var chunk = this.read() || '';
body += chunk;
console.log('chunk: ' + Buffer.byteLength(chunk) + ' bytes');
});
res.on('end', function () {
console.log('body: ' + Buffer.byteLength(body) + ' bytes');
});
req.on('error', function(e) {
console.log("error" + e.message);
});
});
req.end();但这并不能解释这三个电话。(在我的代码中运行您的确切代码时,由于我前面解释的原因,我得到了多行“块”行,但我只得到了一条完整的代码集,只有一条“body”行。)这是更大的测试计划的一部分吗?如果是这样的话,也许它在其他循环中被调用了3次?或者,它可能会导致页面尴尬地刷新或重定向几次,并发送没有发出“结束”信号的标题。我只是不太清楚这个函数在NodeJS中是如何工作的,无法解释这样的异常。
https://stackoverflow.com/questions/30745475
复制相似问题