如何在节点应用程序中使用 fs 读取文件?

how to read file using fs in node app?

我正在尝试使用 fs 模块在 nodejs 中读取此文件。 我收到了两次回复。让我知道我做错了什么。这是我的代码。

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

http.createServer(function(req, res) {
  fs.readFile('sample.txt', function(err, sampleData) {
    console.log(String(sampleData));
    //res.end();
    });
  console.log("The end");
  // res.writeHead(200);
  res.end();
}).listen(2000);

在浏览器中点击端口后。我在我的终端中收到两次响应。这是输出。

The end
this is sample text for the testing.

The end
this is sample text for the testing.

您可以将文件传送给客户端:

fs.createReadStream('sample.txt').pipe(res);

您很可能会收到两次,因为您是从浏览器访问 http://localhost:2000/

这样做时实际上有两个请求。您的实际请求和网站图标 :) 均由您的服务器处理。

查看 Chrome 调试器 -> 网络

将出现两条日志消息:一条用于 /,一条用于 /favicon.ico

您可以通过添加 console.log(req.url);

来验证这一点

要避免这种情况:

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

    http.createServer(function(req, res){
    if(req.url === '/'){  // or if(req.url != '/faicon.ico'){
        fs.readFile('sample.txt', function(err , sampleData){
            console.log(String(sampleData));
            res.end();
        });
    console.log("The end");
    }

    // res.writeHead(200);
}).listen(2000);

自动向 favicon.io 发出请求。 为避免自动请求网站图标,您可以执行以下操作

http.createServer(function(req, res){
    if(req.url != '/favicon.ico'){
        fs.readFile('sample.txt', function(err , sampleData){
            console.log(String(sampleData));
            res.end();
        });
       console.log("The end");
    }

}).listen(2000);

O/p =>

The end.
this is sample text for the testing.