5

I am new to nodejs and callbacks.

So I have this code where I read a file when a request to server is initiated via HTTP:

var http = require("http");
var fs = require("fs");

http.createServer(function(request,response){

    response.writeHead(200,{'Content-Type':'text/plain'});
    response.end("Server runnning...");

    fs.readFile('new.txt',function(err,data){
        if(err){
            console.error(err);
            return;
        }
        console.log(data.toString());
    });

}).listen(1234);

When I run the code, the contents of the file are displayed/logged twice on console.

lorem ipsum
lorem ipsum

The file contents are:

lorem ipsum
1
  • Could you edit the question and add the contents of new.txt to the question? I'm 99.95% sure it's just lorem ipsum, but it helps in helping you to know all the inputs for sure :)
    – mech
    Commented Feb 22, 2016 at 21:13

1 Answer 1

7

When you type a URL into the browser's address bar it will typically make two requests:

  • One for the page you want to see
  • One for /favicon.ico

Two requests means two calls to fs.readFile since you call that for every request.

1
  • It might call OPTIONS request as well. +1 to this answer
    – Dawid Pura
    Commented Feb 22, 2016 at 21:15

Not the answer you're looking for? Browse other questions tagged or ask your own question.