Node.js HTTP 请求返回 2 个块(数据主体)



我正在尝试获取节点中带有HTTP请求的HTML文件的源代码.js - 我的问题是它返回数据两次。这是我的代码:

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("数据从这里开始")的东西时,它返回整个字符串,中间某处有"数据从这里开始",这意味着它只是被拆分了。

我做的每个测试都会返回 2 个值,这真的很烦人。我可以只做"if(chunk.length> 4000)",但考虑到我得到的页面的性质,这可能会改变。我怎样才能使所有数据都以一个大块返回?

这些不是"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();

最新更新