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

Viewed 22836

I have used fs.readFileSync() to read HTML files and it's working. But I have a problem when I use fs.readFile(). May you please help me to resolve the problem? Any help will be appreciated!

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

Using <code>fs.readFileSync</code>

  • Using fs.readFile(). Why can't it read HTML files?
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 Answers

This has to do with a basic concept of Node.js: asynchronous I/O operations. That means that while you are performing I/O, the program can continue its execution. As soon as the data from your file is ready, it will be processed by code in a callback. In other words, the function does not return a value but as its last operation executes the callback passing the data retrieved or an error. This is a common paradigm in Node.js and a common way to handle asynchronous code. The right invocation of fs.readFile() would look like:

fs.readFile(__dirname + "/bai55.html", function (error, html) {
  if (error) {
    throw error;
  }

  const user = "Node JS";
  html = html.replace("{ user }", user);
  res.end(html);
});

Because of readFile use of callback and do not return the data right away.

Look at the node documentation

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

The issue can be resolved by leverlaging 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");
Related