我正在尝试使用node.js中的HTTP请求获取HTML文件的源 - 我的问题是它返回数据两次。这是我的代码:
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',它返回整个字符串,中间某处有“数据从这里开始”,这意味着它只是被分割。
我所做的每个测试都会返回 2 个值,这真的很烦人。我可以只执行“if(chunk.length > 4000)”,但考虑到我得到的页面的性质,这可能会改变。我怎样才能使所有数据返回一大块?
最佳答案
这些不是“2个数据体”,它们是同一主体的2个 block (片),您必须将它们连接起来。
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();
关于javascript - Node.js HTTP 请求返回 2 个 block (数据体),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22015673/