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

问题描述 投票:2回答:3

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

“使用<code fs.readFile() code >>]

我已经使用fs.readFileSync()读取HTML文件,并且可以正常工作。但是我在使用fs.readFile()时遇到问题。您能帮我解决问题吗?任何帮助将不胜感激!使用fs ....

node.js fs
3个回答
6
投票

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


1
投票

由于readFile使用回调,并且不立即返回数据。


0
投票

可以通过杠杆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");
© www.soinside.com 2019 - 2024. All rights reserved.