Reputation: 349
I have just started working on Node.js. I cam across a tutorial in http://net.tutsplus.com/tutorials/javascript-ajax/node-js-for-beginners/, I am trying to execute a script he has given as an example, but it is not working unless i comment out the listener on 'end' event.
var http = require("http");
http.createServer(function (request, response) {
// request.on("end", function () {
response.writeHead(200, {
'Content-Type': 'text/plain'
});
response.end('Hello HTTP!');
// });
//request.end();
}).listen(8080);
The above code is working fine if i am commenting the listener on 'end' for request, but if i un comment it then it is not working correctly.Can somebody help me out here.
Thanks, Harsha.
Upvotes: 0
Views: 117
Reputation: 11541
What actually the request on end
event listener is doing is listen for an end event and trigger a callback function after that event is executed.
You are trying to trigger an end
event even before that event has been executed. Move the request end
function outside the response body and that should work:
var http = require("http");
http.createServer(function (request, response) {
response.writeHead(200, {
'Content-Type': 'text/plain'
});
request.on("end", function () {
console.log("GOOD BYE!");
});
response.end('Hello HTTP!');
}).listen(8080);
Upvotes: 1
Reputation: 100205
The end
event is emitted by the after the response.end()
call, like:
var http = require('http');
http.createServer(function (request, response) {
request.on('end', function () {
console.log('end event called');
});
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Hello HTTP!');
}).listen(8080);
Upvotes: 1