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 \033[90m request complete!\033[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 \033[90m' + query.parse(body).name + '\033[39m\n'); }); }).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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With