The res.sendFile() allows users to render HTML files in node express js. In this tutorial, we will learn how to render HTML files in node js express using res.SendFile() function.
How to Render HTML Files in Node JS Express
Steps to render html file data or plain HTML in node js express:
Step 1 – Create Node JS App
Run the following command on cmd to create node js application:
mkdir my-app cd my-app npm init -y
Step 2 – Install Express
In this step, run following command to install express in node js app:
npm install express
Step 3 – Create Server.js File
In this step, you need to create server.js
file and add the following code into it:
var express = require('express'); var app = express(); app.get('/',function(req,res) { res.sendFile(__dirname + '/index.html'); }); app.listen(3000, () => console.log(`App listening on port 3000`))
Step 4 – Create index.html File
In this step, create index.html
file and update the following code into it:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> <p>This is sample html file - Tutsmake.com!</p> </body> </html>
Step 5 – Start Development Server
You can use the following command to run development server:
//run the below command npm start after run this command open your browser and hit http://127.0.0.1:3000/
Conclusion
That’s it, we have learned how to render html files in node js express.