readfile()回调调用两次 [英] readfile() callback called twice

查看:124
本文介绍了readfile()回调调用两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是nodejs和callbacks的新手。

I am new to nodejs and callbacks.

所以我有这个代码,当我通过HTTP发起对服务器的请求时我读取文件:

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

文件内容为:

lorem ipsum


推荐答案

当您在浏览器的地址栏中键入URL时,它通常会发出两个请求:

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


  • 您要查看的页面一个

  • 一个用于 / favicon。 ico

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

两个请求意味着两次调用 fs.readFile 因为你为每个请求都打电话。

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

这篇关于readfile()回调调用两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆