How to Render HTML File in Node JS Express
In this article, we will explain to you how to render HTML file in node js Express. sometimes we need to render the HTML file in node js.
We will create a node js application with express. An express is a nodejs npm package that helps to render the HTML page into the nodejs application.
Node Js Application Setup
First, we will open the command prompt and create the application in our directory. for this, you can follow the below command.
1 2 3 | mkdir my_node_app cd my_node_app npm init |
Install NPM Package
After the done setup node js application, we will install the express npm package. so you can see the following npm command.
1 | npm install express --save |
Render HTML web pages
In this step, We will render HTML web pages using sendFile function. so you can see our server.js file example.
server.js
1 2 3 4 5 6 7 8 9 10 | var express=require('express'); var app = express(); app.get('/',function(req,res){ res.sendFile(__dirname + '/index.html'); }); app.listen(3000,function(){ console.log("Express Started on Port 3000"); }); |
Create a new index.html file and open it paste below code.
index.html
1 2 3 4 5 6 7 8 9 10 11 12 | <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> <p>This is index html file</p> </body> </html> |
Run Node js Application
we will run the node js application using the below command. so you can follow the below command.
1 | node server.js |
Now you can run the example using the below Url in the browser.
1 | http://localhost:3000 |