Render HTML file in Node.js and Express.js framework

render html express

ExpressJS is a popular NodeJS web framework. ExpressJS allows you to develop a custom web server according to your project requirement. The express project can be extended by installing various node modules. However, you don’t need to install multiple packages to handle HTML files and to render them in the response.

In this short tutorial, I am going to explain to you how to render HTML files in a custom NodeJS and ExpressJS Server. You don’t need to install any extra modules to render an HTML file in Express. Just install express and you are good to go.

Step 1: Install Express

Create a new folder and initialize a new Node project using the following command.

npm init --y

Let’s install Express.

npm install --save express

Great. let’s move forward and learn about the function we are going to use to render HTML file in Express.

Step 2: Using sendFile() function

ExpressJS provides sendFile() function which will basically send HTML files to browser which then automatically interpreted by browser. All we need to do is in every route to deliver an appropriate HTML file.

For.eg :
When user hit main URL deliver index.html :

//assuming app is express Object.
app.get('/',function(req,res) {
  res.sendFile('index.html');
});

This code is for example purpose. It will cause directory resolution error.

Step 3: Render HTML in Express

I am going to develop a simple website consisting of 3 pages i.e Home page, about page, site link page. I will use Bootstrap for designing and jQuery for event handling.

Directory structure :

----- node_modules
|--+express
---+ index.html
---+ about.html
---+ index.html
--- app.js
----package.json
package.json
{
    "name": "htmlRender",
    "version": "1.0.0",
    "description": "",
    "main": "index.js",
    "scripts": {
        "test": ""
    },
    "keywords": [],
    "author": "",
    "license": "ISC",
    "dependencies": {
        "express": "^4.16.4"
    }
}

Here is our express Server code.

app.js
const express = require('express');
const app = express();
const path = require('path');
const router = express.Router();

router.get('/',function(req,res){
  res.sendFile(path.join(__dirname+'/index.html'));
  //__dirname : It will resolve to your project folder.
});

router.get('/about',function(req,res){
  res.sendFile(path.join(__dirname+'/about.html'));
});

router.get('/sitemap',function(req,res){
  res.sendFile(path.join(__dirname+'/sitemap.html'));
});

//add the router
app.use('/', router);
app.listen(process.env.port || 3000);

console.log('Running at Port 3000');

Here is our HTML files. I am going to show index.html only.

index.html
<html>
<head>
  <title>Express HTML</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap-theme.min.css">
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
</head>
<body>
  <div style="margin:100px;">
   

Here is the output.
homepage

Step 4: Render Dynamic HTML using templating engine

In the code shown above, we render static HTML files. However, there are scenarios where we need to render dynamic HTML templates. Before you get confused between static and dynamic templates, let me explain a difference quickly.

In static templates, we cannot pass custom variables and customize the template based on our needs. In dynamic templates, we can pass dynamic variables and render HTML files with different values.

Let’s build a simple project to understand the templating in Express. I am going to use pug templating engine which is very popular and recommended by Express as well. We use Pug for this website as well, in fact, this page is rendered using Pug templates.

Let’s install our dependencies.

npm i --S express pug

Here is our Express server code.

app.js
const express = require("express");
const app = express();
const path = require("path");
const router = express.Router();

app.set("view engine", "pug");
app.set("views", path.join(__dirname, "views"));

router.get("/", (req, res) => {
  res.render("index");
});

router.get("/about", (req, res) => {
  res.render("about", { title: "Hey", message: "Hello there!" });
});

app.use("/", router);
app.listen(process.env.port || 3000);

console.log("Running at Port 3000");

Observe in routers, we are passing dynamic values to Pug templates. Here is the code of Pug templates residing in the views directory.

index.pug
html
  head
    title Render HTML using PUG
  body
    h1 Welcome
about.pug
html
  head
    title= title
  body
    h1= message

After running this code, navigate your browser to localhost:3000/about, you should see an HTML output rendered using Pug templates.

Awesome. These values can be fetched from a database or any other source and rendered using Pug templates.

Related articles about Databases: Database Tutorials

Further reading

Read some of our best tutorials.

Conclusion:

There are scenarios where you need to develop a web server that delivers HTML files like how your apache does. However, this is not the optimal use of Node.js but you can use such a feature to achieve a custom web server for your own application.

54 thoughts on “Render HTML file in Node.js and Express.js framework”

  1. I am new in nodejs and express js. please,help me

    inside view only I gave css, js,image file and html also but i am not get.
    localhost:3000/dashboard
    Error: ENOENT, stat ‘C:dashboard.html’

    var express = require("express");
    var app     = express();
    app.use(express.static(__dirname + '/view'));

    app.get('/dashboard',function(req,res){
      res.sendFile('/dashboard.html');
    });

    app.get('/index1',function(req,res){
      res.sendFile('/index.html');
    });
    app.get('/',function(req,res){
      res.redirect("/login.html");
    });


    app.listen(3000);

    console.log("Running at Port 3000");
    1. Here you go.

      var express = require("express");
      var app     = express();
      var path    = require("path");

      app.use(express.static(__dirname + '/view'));

      app.get('/dashboard',function(req,res){
        res.sendFile((path.join(__dirname + '/dashboard.html'));
      });

      app.get('/index1',function(req,res){
        res.sendFile((path.join(__dirname+'/index.html'));
      });
      app.get('/',function(req,res){
        res.redirect('/login');
      });
      app.get('/login',function(req,res){
        res.redirect((path.join(__dirname + '/login'));
      });

      app.listen(3000);

      console.log("Running at Port 3000");
  2. How to get the value from the html file.e.g i want to display the username from login page in console.how can i?

  3. Hi,
    In my application, I have “index.html” in app folder, and other pages are in “app/views” folder. Now when I use app.get(), I am able to access only the pages in views folder.
    How to load views as part of “index.html” so that it will be a Single Page Application.??

    Please help I am stuck here… 🙂

    1. I am also troubling to get record in html , how could i get response object on html page ?

  4. Good afternoon,

    I am having a small problem, where in my html pages I have referred to bootstrap via a relative path to a directory on the server e.g.

    Where as in your example you have used a CDN. So when the index.html loads, it brings up the page, but not the bootstrap.

    __dirname thinks it is in D:DropboxAptana 3 WorkspacemyLibrary

    So I have “assumed that the index.html page would use that as it’s base location of __dirname for loading the additional bootstrap files?

    If I load up the index.html via a browser on it’s own, the bootstrap all appears.

    1. Please add static path where your bootstrap resides.

      express.static(__dirname + '/folder where bootstrap is')

      After that add boostrap.css or .js in index.html and it should work.

  5. i want fetch data from sql server using node js and bind with html page using angula js .
    i just want know is it possible ??

  6. Thank you so much your post saved me after hours of searching.
    Can I use my only server.js to serve all my html pages?

  7. Is there a way that you can have all of the files registers/sent without having to declare this in your code? For example, setting up a node server you could say /index.html and this file will display on your new server.

  8. I am not able to load css even after adding static path using app.use(express.static(__dirname + ‘/assets’)); in server.js

  9. Great tutorial! You can almost never find a client side template rendering example for express on the web, you always find jade server side templating examples. This helped a ton for setting up my nodejs server as an email service with sendgrid without getting a 502 bad gateway error. Thanks!

  10. i want to go to a particular element using the element id. Is it possible using the res.sendFile(path.join(__dirname, ‘filename.html#idtag’));

  11. Done… how to include Css file style and Js ? because include in html file not working css and js include.

  12. Can you please update me about restify framework. Basic APIs like get , post, put, delete will be enough. 🙂

  13. Hi,
    I am trying to implement a blog application using NodeJs, Express and MongoDb. I am struggling with displaying the data as I am piping images using Read Stream. When I try to do a res.render(). It throws error saying can’t set headers after they are sent. I know I am sending the response twice to the browser, but I can’t find a work-aroud for this.
    app.get(‘*’, function (req, res) {
    var file = path.join(dir, req.path.replace(/\/$/, ‘/index.html’));
    if (file.indexOf(dir + path.sep) !== 0) {
    return res.status(403).end(‘Forbidden’);
    }
    var type = mime[path.extname(file).slice(1)] || ‘text/plain’;
    var s = fs.createReadStream(file);
    s.on(‘open’, function () {
    res.set(‘Content-Type’, type);
    s.pipe(res);
    });
    s.on(‘error’, function () {
    res.set(‘Content-Type’, ‘text/plain’);
    res.status(404).end(‘Not found’);
    });
    var cursor = db.collection(‘quotes’).find().toArray((err, result) => {
    if (err) return console.log(err)
    // renders index.ejs
    //res.render(‘index’, {quotes: result})
    })
    })

    1. Shahid (UnixRoot) Shaikh

      Put return at the status code.

      s.on(‘error’, function () {
      res.set(‘Content-Type’, ‘text/plain’);
      return res.status(404).end(‘Not found’);
      });
  14. thanks so much for this, really helped me understand the node-express way of rendering pages based on requests made. My question is, can one use a master template html page and make it a default layout engine like handlebars?

  15. Hey there! We’re excited to help you out. Let us know your email address so that we can follow up in case we get disconnected.

  16. Hello Shahid, I am trying to get a simple html file that lets users know what an app I am working on does, but I cannot seem to get it to work.

  17. how can I pass data to that html file from server.js? and how can I display that dynamic data in that html file?

  18. Is it possible to redirect or stream a video along with html from the server itself. Imean I wish to stream the video into an or a tag from my local machine to index.html file using server.js file. I have learned how to stream video using nodejs but I am unknown about how to place it onto a html file within some container.

  19. Maybe I’ve just not yet had enough coffee, but your code `res.sendFile(path.join(__dirname+’/sitemap.html’));` seems to be missing the point of `path.join` as JS will evaluate `__dirname+’/sitemap.html’` to a single value, and so the `join` function is only being passed one argument

  20. Hi there!very well done with your article. Is it still relevant as it’s a few years old?I’m asking this because I’ve tried your method and it didn’t work, I made a path to my js files by defining a /public folder and I can clearly see them if I do localhost:9000/public/MY SCRIPT. js but the script is not loaded in my page.
    My script only contains a console.log for testing but nothing happens. CSS works fine but js is totally ignored, is there any security settings that might be blocking it?

  21. i want to render a html page where html page again use a .js plugin file..but where it is throwing an error plugin .js file is not bale to load using fs module..any suggestion on dat..

  22. Hi,

    I am running my web application on localhost. How can i make it to run as client server? Means i want to run it on web that can be access by others. Need change IP address or create a server.

    Thanks in advacnce.

  23. hello I did the same process and created a root folder auth, inside this there is one another folder that is password where html file is stored and same inside it again there are another folders for css, images, js and another files, I’m including using exports.render_reset_password_template = function(forgotpassModel, res) { //template path!!//
    return res.sendFile(path.resolve(‘./auth/password/css/main.css’));
    }; and rendering with html file like exports.render_reset_password_template = function(forgotpassModel, res) { //template path!!//
    return res.sendFile(path.resolve(‘./auth/password/reset-password.html’));
    }; but I’m confused with it what’s wrong with it??

  24. After the post method is done, i want to show an alert on the browser that job is done and let the user be on the same page without navigating to other. Please suggest.

  25. I have a problem adding a image on html. Not found the file .png

    I put the image in the same folder with html file.
    I used , but in the browser dont show it.

    What is wrong?, please.

  26. you can use body-parser and store all data on an object like this—>
    install body-parser by using command –> npm i body-parse
    requiring all modules like this—>
    const bodyParser=require(‘body-parser’);
    app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
    extended: true
    }));
    //getting data from html page by usnig name property.
    var obj={
    empId:req.body.empId,
    empName:req.body.empName,
    empSalary:req.body.emSalary,
    empDesig:req.body.empDesig,
    }

    console.log(obj)

Comments are closed.