Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

node.js

fs

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>

like image 325
Dang Hoang Avatar asked Nov 21 '17 09:11

Dang Hoang


1 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);
});
like image 155
ilmirons Avatar answered Sep 23 '22 14:09

ilmirons