Serving HTML files using ExpressJS and NodeJS


Sometimes it is required to just wrap up a simple NodeJS server using the ExpressJS framework and get started with building an app without getting into the complexity of creating template files and serving them. So one can just create a simple html file and serve it over the server using ExpressJS.

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

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

app.listen(process.env.PORT, process.env.IP, function() {
    console.log("Started listening on your server");

As you can see above, make sure that you add the path prefix to make this to work. The sendFile function requires the absolute path for it to work.

Leave a Reply