Node.js HTTP请求返回2个块(数据体) [英] Node.js HTTP request returns 2 chunks (data bodies)
问题描述
我正在尝试在node.js中获取带有HTTP请求的HTML文件的来源 - 我的问题是它返回两次数据。这是我的代码:
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. 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();
然后返回:
5637
3703
地狱!当我只是console.log(chunk)时,它返回所有数据,好像它是一个大字符串,当我在res.on('data')中添加类似console.log(data starts here)之类的东西时,它返回整个字符串,其中数据从这里开始位于中间某处,暗示它只是被拆分。
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.
我做的每个测试都返回2个值,这真的很烦人。我可以做if(chunk.length> 4000),但考虑到我所获得的页面的性质,这可能会改变。我怎样才能使所有数据在一个大块中返回?
Every test I do returns 2 values and it's really annoying. I can just do "if(chunk.length > 4000)" but given the nature of the page I'm getting, this could change. How can I make it so that all the data returns in one large chunk?
推荐答案
这些不是2个数据主体,这些是同一个主体的2个块(件),你必须将它们连接起来。
These are not "2 data bodies", these are 2 chunks(pieces) of the same body, you have to concatenate them.
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();
这篇关于Node.js HTTP请求返回2个块(数据体)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!