Sometimes, we want to load basic HTML in Node.js and JavaScript.
In this article, we’ll look at how to load basic HTML in Node.js and JavaScript.
How to load basic HTML in Node.js and JavaScript?
To load basic HTML in Node.js and JavaScript, we use the http
module.
For instance, we write
const http = require("http");
const fs = require("fs");
fs.readFile("./index.html", (err, html) => {
if (err) {
throw err;
}
http
.createServer((request, response) => {
response.writeHeader(200, { "Content-Type": "text/html" });
response.write(html);
response.end();
})
.listen(8000);
});
to call readFile
to read index.html into a string.
Then we get the string from the html
parameter in the callback.
Next, we call http.createServer
with a callback to create a HTTP server.
The callback serves the response by calling response.write
with html
to serve the html
string as the response body.
Conclusion
To load basic HTML in Node.js and JavaScript, we use the http
module.