[英]Node.js HTTP request returns 2 chunks (data bodies)
I'm trying to get the source of an HTML file with an HTTP request in node.js - my problem is that it returns data twice. 我试图在node.js中获取带有HTTP请求的HTML文件的来源 - 我的问题是它返回两次数据。 Here is my code: 这是我的代码:
var req = http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
if(chunk.length > 1000) {
console.log(chunk.length);
}
});
req.on('error', function(e) {
console.log("error" + e.message);
});
});
req.end();
This then returns: 然后返回:
5637
3703
The hell! 地狱! When I just console.log(chunk), it returns all the data as if it were one large string, and when I add a something like console.log("data starts here") in the res.on('data', it returns the whole string with the "data starts here" somewhere in the middle, implying it's just being split. 当我只是console.log(chunk)时,它返回所有数据,好像它是一个大字符串,当我在res.on('data'中添加类似console.log(“data starts here”)的东西时,它返回整个字符串,其中“data starts here”位于中间的某个位置,暗示它只是被拆分。
Every test I do returns 2 values and it's really annoying. 我做的每个测试都返回2个值,这真的很烦人。 I can just do "if(chunk.length > 4000)" but given the nature of the page I'm getting, this could change. 我可以做“if(chunk.length> 4000)”,但考虑到我所获得的页面的性质,这可能会改变。 How can I make it so that all the data returns in one large chunk? 我怎样才能使所有数据在一个大块中返回?
These are not "2 data bodies", these are 2 chunks(pieces) of the same body, you have to concatenate them. 这些不是“2个数据主体”,它们是同一个主体的2个块(件),你必须连接它们。
var req = http.request(options, function(res) {
var body = '';
res.setEncoding('utf8');
// 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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.