Akshat Jiwan Sharma Akshat Jiwan Sharma - 1 month ago 12
Node.js Question

Any way to serve static html files from express without the extension?

I would like to serve an html file without specifying it's extension. Is there any way I can do this without defining a route? For instance instead of

/helloworld.html


I would like to do just

/helloworld

Answer

A quick'n'dirty solution is to attach .html to requests that don't have a period in them and for which an HTML-file exists in the public directory:

var fs        = require('fs');
var publicdir = __dirname + '/public';

app.use(function(req, res, next) {
  if (req.path.indexOf('.') === -1) {
    var file = publicdir + req.path + '.html';
    fs.exists(file, function(exists) {
      if (exists)
        req.url += '.html';
      next();
    });
  }
  else
    next();
});
app.use(express.static(publicdir));