Reputation: 3098
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
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 :
http://nodejs.org/api/http.html#http_http_request_options_callback
The optional callback parameter will be added as a one time listener for the 'response' event.
'response' event http://nodejs.org/api/http.html#http_event_response
The response argument will be an instance of http.IncomingMessage.
http.IncomingMessage http://nodejs.org/api/http.html#http_http_incomingmessage
It implements the Readable Stream interface.
Readable Stream 'end' event http://nodejs.org/api/stream.html#stream_event_end
Upvotes: 7