Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

readfile() callback called twice

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
like image 968
goelakash Avatar asked Feb 22 '16 21:02

goelakash


People also ask

What does the readFile () method require?

readFile() Method. Parameters: The method accept three parameters as mentioned above and described below: filename: It holds the name of the file to read or the entire path if stored at other location. encoding: It holds the encoding of file.

Does readFile return anything?

readFile. Returns the contents of the file named filename. If encoding is specified then this function returns a string. Otherwise it returns a buffer.

What two parameters are passed to the callback in the FS readFile method?

callback : A function with two parameters: error and data .

What is the difference between readFileSync and readFile?

readFileSync() is synchronous and blocks execution until finished. These return their results as return values. readFile() are asynchronous and return immediately while they function in the background.


1 Answers

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.

like image 101
Quentin Avatar answered Oct 21 '22 02:10

Quentin