【问题标题】:How do I use `fs.readFile` to read an HTML file in Node.js?如何使用 `fs.readFile` 在 Node.js 中读取 HTML 文件?
【发布时间】:2018-05-04 16:54:23
【问题描述】:

我使用fs.readFileSync() 来读取 HTML 文件并且它正在工作。但是我在使用fs.readFile() 时遇到了问题。你能帮我解决这个问题吗?任何帮助将不胜感激!

  • 使用fs.readFileSync():
const http = require("http");
const fs = require("fs");

http.createServer((req, res) => {
  res.writeHead(200, {
    "Content-type": "text/html"
  });

  const html = fs.readFileSync(__dirname + "/bai55.html", "utf8");
  const user = "Node JS";

  html = html.replace("{ user }", user);
  res.end(html);
}).listen(1337, "127.0.0.1");

  • 使用fs.readFile()。为什么不能读取 HTML 文件?
const http = require("http");
const fs = require("fs");

http.createServer((req, res) => {
  res.writeHead(200, {
    "Content-type": "text/html"
  });

  const html = fs.readFile(__dirname + "/bai55.html", "utf8");
  const user = "Node JS";

  html = html.replace("{ user }", user);
  res.end(html);
}).listen(1337, "127.0.0.1");

【问题讨论】:

    标签: node.js fs


    【解决方案1】:

    因为readFile使用了回调,并没有马上返回数据。

    node documentation

    fs.readFile('/etc/passwd', (err, data) => {
      if (err) throw err;
      console.log(data);
    });
    

    【讨论】:

      【解决方案2】:

      这与 Node.js 的一个基本概念有关:异步 I/O 操作。这意味着当您执行 I/O 时,程序可以继续执行。一旦您的文件中的数据准备就绪,它将由回调中的代码处理。换句话说,该函数不返回值,而是在其最后一个操作执行回调时传递检索到的数据或错误。这是 Node.js 中的常见范例,也是处理异步代码的常用方法。 fs.readFile() 的正确调用如下所示:

      fs.readFile(__dirname + "/bai55.html", function (error, html) {
        if (error) {
          throw error;
        }
      
        const user = "Node JS";
        html = html.replace("{ user }", user);
        res.end(html);
      });
      

      【讨论】:

        【解决方案3】:

        这个问题可以通过Promise解决

        const fs = require('fs');
        const http = require("http");
        
        const fsReadFileHtml = (fileName) => {
            return new Promise((resolve, reject) => {
                fs.readFile(path.join(__dirname, fileName), 'utf8', (error, htmlString) => {
                    if (!error && htmlString) {
                        resolve(htmlString);
                    } else {
                        reject(error)
                    }
                });
            });
        }
        
        http.createServer((req, res) => {
            fsReadFileHtml('bai55.html')
                .then(html => {
                    res.writeHead(200, {
                        "Content-type": "text/html"
                    });
                    res.end(html.replace("{ user }", "Node JS"));
                })
                .catch(error => {
                    res.setHeader('Content-Type', 'text/plain');
                    res.end(`Error ${error}`);
                })
        }).listen(1337, "127.0.0.1");
        

        【讨论】:

          猜你喜欢
          • 2012-03-15
          • 2015-02-01
          • 2019-05-18
          • 1970-01-01
          • 1970-01-01
          • 2016-05-25
          • 2011-11-05
          • 2020-07-01
          • 1970-01-01
          相关资源
          最近更新 更多