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

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

Posted by: admin November 30, 2017 Leave a comment

Questions:

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
Answers:

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));

Questions:
Answers:

you can just use extension option in express.static method .

app.use(express.static(path.join(__dirname, 'public'),{index:false,extensions:['html']}));

Questions:
Answers:

While Robert’s answer is more elegant there is another way to do this. I am adding this answer just for the sake of completeness. To serve static files without extension you can create a folder with the name of the route you want to serve against and then create an index.html file in it.

Taking my own example if I wanted to serve hello.html at /hello. I would create a directory called hello and put an index.html file in it. Now when ‘/hello’ is called express will automatically serve this file without the extension.

Kind of obvious as this is supported by all web frameworks but I missed it back then.

Questions:
Answers:

If you want to go the reverse way like I did(serving an html file called “helloworld” as html) this is the middleware I used.

var express = require('express');
var app = express();

app.use(function(req, res, next) {
  if (req.path.indexOf('.') === -1) {
    res.setHeader('Content-Type', 'text/html');
  }
  next();
});

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

app.listen(8080, function () {
  console.log('App listening on port 8080!');
})