UPDATE:
Even though another request is being sent for favicon.ico
and function is getting executed again (two console.log(data) outputs), why isn't the response object being sent twice?
Also, is there a way to not send a request for favcion.ico as I wouldn't want my function to uselessly run twice?
I have created a very simple servlet to accept a GET (default) and return the contents to the browser after reading a file
var http = require("http");
var fs = require("fs");
var num=0;
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
var data = '';
// Create a readable stream
var readerStream = fs.createReadStream('input.txt');
// Set the encoding to be utf8.
readerStream.setEncoding('UTF8');
// Handle stream events --> data, end, and error
readerStream.on('data', function(chunk) {
data += chunk;
});
readerStream.on('end',function(){
console.log(data); //To print same file content in the console
response.end(data);
});
readerStream.on('error', function(err){
console.log(err.stack);
data+="\n\n"+err.stack;
});
}).listen(8081);
// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');
But every time I run this servlet and make a request at http://localhost:/8081, I get the content of the file printed twice on the console but only once at the browser window (this is the expected behaviour).
What is the cause for the console behaviour?
Also, I modified the program by adding a counter to count how many times the function is run for every request (appended the value as data+num
for both console
and response
) and it was found to be two but the response from the first execution of the function was the one received by the browser, not the second one(browser window printed data+1 for the first ever request).