Tuesday, 4 April 2017

nodejs req.on('end', callback) doesn't work property

I am currently buildings proxy using nodejs, which use following syntax for sending and receiving https request and response. However in my project, the response is a liitle bit larger, so typically, req.on('data', callback) will be called 5~7 times before req.on('end', callback) being called.

Here is the simplified code structure:

var http = require("https");
var options = {
    hostname: '<WEB SERVICE>',
    port: 80,
    path: '<WEB PATH>',
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    }
};
var response = "";
var req = http.request(options, function(res) {
    res.setEncoding('utf8');
    res.on('data', function (body) {
        console.log("data");
        response += body;
    });

    res.on('end', function () { 
        console.log("end");
        response = "";
    });
});
req.on('error', function(e) {
     console.log('problem with request: ' + e.message);
});
// write data to request body
req.write('<SOMETHING>');
req.end();

Ideally, when multiple request comes in, the logging sequence shall be:

data, data, data, data, data, end, data, data, data, data, end

i.e. once one request is done, end will be called once.

However, after doing several tests, when response is big. The sequence becomes:

<response 1 comes>data, data, data ..... data <response 2 comes> data, data,       data, ..., data, end

i.e. the end for request 1 is missing.

In short, we need to make sure the callback of 'end' is called exactly once immediate after doing several call back of req.on('data', callback).

I believe there must be some common method for solving this issues (seems a classic bugs in node) and would be appreciated if anyone can indicate how to solve this property.

Thanks for the help!



via Chen Chen

No comments:

Post a Comment