readfile() callback called twice

匿名 (未验证) 提交于 2019-12-03 01:34:02

问题:

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:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!