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

7

我已经使用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");

使用<code>fs.readFileSync</code>

  • 使用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");

Using <code>fs.readFile()</code>

3个回答

11

这与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);
});

2

通过利用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");

2
由于readFile使用回调而不立即返回数据,因此需要等待回调完成后才能获得数据。
请参考node文档中的说明
fs.readFile('/etc/passwd', (err, data) => {
  if (err) throw err;
  console.log(data);
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接