Render HTML file in ExpressJS

ExpressJS allows you to develop custom web server according to your need. You don’t need to install multiple packages to handle HTML files. If you have Node.js installed, you are good to go.

In this short tutorial i am going to explain how to render HTML files in ExpressJS.

About 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 deliver 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.

Our project :

I am going to develop simple website consist 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
--- Server.js
----package.json
package.json
{
  "name": "express-html",
  "version": "0.0.1",
  "dependencies": {
    "express": "^4.11.0"
  }
}

Install dependencies using

npm install

and run project using

node Server.js

Here is our express Server.

Server.js
var express = require("express");
var app     = express();
var path    = require("path");


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

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

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

app.listen(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;">
    <nav class="navbar navbar-inverse navbar-static-top">
  <div class="container">
    <a class="navbar-brand" href="/">Express HTML</a>
    <ul class="nav navbar-nav">
      <li class="active">
        <a href="/">Home</a>
      </li>
      <li>
        <a href="/about">About</a>
      </li>
      <li>
        <a href="/sitemap">Sitemap</a>
      </li>
    </ul>
  </div>
</nav>
    <div class="jumbotron"  style="padding:40px;">
      <h1>Hello, world!</h1>
      <p>This is a simple hero unit, a simple jumbotron-style component for calling extra attention to featured content or information.</p>
      <p><a class="btn btn-primary btn-lg" href="#" role="button">Learn more</a></p>
    </div>
  </div>
</body>
</html>

Here is the output.
homepage

Final words:

Right now we are resolving path in each router. You can optimize this little bit. Express have configuration variable which let’s you define static file path so that you don’t need to resolve path in every routes. Here is how to do so.

var express = require("express");
var app     = express();
app.use(express.static(__dirname + '/View'));
//Store all HTML files in view folder.
app.use(express.static(__dirname + '/Script'));
//Store all JS and CSS in Scripts folder.

app.get('/',function(req,res){
  res.sendFile('index.html');
  //It will find and locate index.html from View or Scripts
});

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

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

app.listen(3000);

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

This code will work in similar way as above one.

Conclusion:

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

Shahid (UnixRoot) Shaikh

Hey there, This is Shahid, an Engineer and Blogger from Bombay. I am also an Author and i wrote a programming book on Sails.js, MVC framework for Node.js.

Related Posts

39 Comments

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

    inside view only i given css,js,image file and html also but i am not get.
    http://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… 🙂

  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. Can you please update me about restify framework. Basic APIs like get , post, put, delete will be enough. 🙂

  12. 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})
    })
    })

  13. 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?

  14. 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.

  15. 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.

Leave a Reply

Your email address will not be published. Required fields are marked *