Readfile () callback called twice

I am new to nodejs and callbacks.

So, I have this code where I read the file when a server request 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 / registered twice on the console.

lorem ipsum
lorem ipsum

File contents:

lorem ipsum
+4
source share
1 answer

When you enter the URL into the address bar of the browser, it usually performs two requests:

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

Two requests mean two calls fs.readFile, as you call this for each request.

+7
source

Source: https://habr.com/ru/post/1629955/


All Articles