nodejs read html file code example
Example 1: show html file on nodejs code
let http = require('http');
let fs = require('fs');
let handleRequest = (request, response) => {
response.writeHead(200, {
'Content-Type': 'text/html'
});
fs.readFile('./index.html', null, function (error, data) {
if (error) {
response.writeHead(404);
respone.write('Whoops! File not found!');
} else {
response.write(data);
}
response.end();
});
};
http.createServer(handleRequest).listen(8000);
Example 2: read html file node js
const http = require("http");
const fs = require("fs");
const hostname = "127.0.0.1";
const port = 3000;
const files = fs.readFileSync("new.html");
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader("Content-Type", "text/html");
res.end(files);
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
console.log("Done")
});