mritz_p
mritz_p

Reputation: 3098

Why does node.js http doesn't call the end event when there is no data listener?

I am sending data from a file to a server as a HTTP POST request like that:

var options = {
    "hostname": "example.com",
    "port": 42,
    "path": "/whatever",
    "method": "PUT",
    "headers" : {
        // a few headers
    }
};

var req = http.request(options, function(res) {
    res.on("end", function () {
        console.log("The request is finished");
    });
});

var stream = fs.createReadStream("/tmp/someFile");

stream.on("data", function(data) {
    req.write(data);
});

stream.on("end", function() {
    req.end();
});

I am listening for res.on("end") in order to do more stuff after the file is uploaded.

However, in the example above, the res.on("end") is never called.

What is striking, is that when I add a listener for the data event, res.on("end") is called reliably.

This even works if I completely ignore the data as in the example below:

var options = {
    "hostname": "example.com",
    "port": 42,
    "path": "/whatever",
    "method": "PUT",
    "headers" : {
        // a few headers
    }
};

var req = http.request(options, function(res) {
    res.on("data", function () {
        /*
         * I don't even care for the data returned...
         */
    });

    res.on("end", function () {
        console.log("The request is finished");
    });
});

var stream = fs.createReadStream("/tmp/someFile");

stream.on("data", function(data) {
    req.write(data);
});

stream.on("end", function() {
    req.end();
});

Is this a bug? Is it the expected behaviour? Am I doing something wrong creating the request or reading the data from file?

Upvotes: 5

Views: 4737

Answers (1)

jillro
jillro

Reputation: 4559

This is the expected behavior.

http://nodejs.org/api/stream.html#stream_event_end

Event: 'end'

This event fires when no more data will be provided.

Note that the end event will not fire unless the data is completely consumed. This can be done by switching into flowing mode, or by calling read() repeatedly until you get to the end.

From the doc :

Upvotes: 7

Related Questions