【问题标题】:how to read file using fs in node app?如何在节点应用程序中使用 fs 读取文件?
【发布时间】:2017-10-28 21:58:56
【问题描述】:

我正在尝试使用 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.

【问题讨论】:

  • 代码不起作用。结果不适合它。
  • sample.txt 包含“这是用于测试的示例文本。”

标签: javascript node.js http fs


【解决方案1】:

您很可能会得到两次,因为您正在从浏览器访问http://localhost:2000/。

这样做时实际上有两个请求。您的实际请求和 favicon :) 两者都由您的服务器处理。

看看 Chrome 调试器 -> 网络

【讨论】:

  • 哦..现在我明白了。
【解决方案2】:

将出现两条日志消息:一条用于 /,一条用于 /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);

【讨论】:

  • 这个条件对我有用 >>if(req.url != '/favicon.ico')
【解决方案3】:

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

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.

【讨论】:

    【解决方案4】:

    您可以将文件通过管道发送到客户端:

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

    【讨论】:

    • 我想在终端控制台查看响应。我得到了两次res。我只是想知道为什么我得到了两次。
    猜你喜欢
    • 2015-02-02
    • 1970-01-01
    • 2015-06-07
    • 2015-11-06
    • 1970-01-01
    • 2020-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多