如何使用 `fs.readFile` 读取 Node.js 中的 HTML 文件?

How do I use `fs.readFile` to read an HTML file in Node.js?

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

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");

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");

因为 readFile 使用了回调,所以不return 立即获取数据。

看看node documentation

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

这与 Node.js 的一个基本概念有关:异步 I/O 操作。这意味着当您执行 I/O 时,程序可以继续执行。一旦文件中的数据准备就绪,回调中的代码就会对其进行处理。换句话说,该函数不 return 一个值,而是在其最后一个操作执行回调时传递检索到的数据或错误。这是 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);
});

可以通过 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");