Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
79
rated 0 times [  80] [ 1]  / answers: 1 / hits: 31287  / 10 Years ago, thu, may 22, 2014, 12:00:00

So I have a simple client application communicating with a server side application in node.js. On the client side, I have the following code:



function send (name) {
http.request({
host: '127.0.0.1',
port: 3000,
url: '/',
method: 'POST'
}, function (response) {
response.setEncoding('utf8');
response.on('data', function (data) {
console.log('did get data: ' + data);
});
response.on('end', function () {
console.log('n 33[90m request complete!33[39m');
process.stdout.write('n your name: ');
});
response.on('error', function (error) {
console.log('n Error received: ' + error);
});
}).end(query.stringify({ name: name})); //This posts the data to the request
}


The odd part is, if I don't include the 'data' event via:



    response.on('data', function (data) {
console.log('did get data: ' + data);
});


The 'end' event for the response is never fired off.



The server code is as follows:



var query = require('querystring');
require('http').createServer(function (request, response) {
var body = '';
request.on('data', function (data) {
body += data;
});
request.on('end', function () {
response.writeHead(200);
response.end('Done');
console.log('n got name 33[90m' + query.parse(body).name + '33[39mn');
});
}).listen(3000);


I would like to know why this is happening when the documentation (to my knowledge) doesn't require you to listen in on the data event in order to close a response session.


More From » node.js

 Answers
41

The 'end' is invoked only when all the data was consumed, check the reference below:




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.




But why you need to call the .on('data',..)? The answer is




If you attach a data event listener, then it will switch the stream
into flowing mode, and data will be passed to your handler as soon as
it is available.




So basically by adding the data listener, it changes the stream into flowing mode and starts consuming the data.



Please check this link for more reference about it.


[#70887] Wednesday, May 21, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
rohan

Total Points: 403
Total Questions: 93
Total Answers: 105

Location: Trinidad and Tobago
Member since Mon, Jul 13, 2020
4 Years ago
;