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!
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");
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");
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With