Autostrada
The vast majority of web servers have a www
directory containing static files. Node.js servers are no exception. The problem with these is that file routing is done "manually"; each file must be associated with an URL (yes I didn't know about Express static). As it was a recurring problem in my projects, I decided to create an NPM module that handles routing once and for all: Autostrada.
Routing is done dynamically. That is, if a file is added or deleted, the routing will be automatically updated without the need to restart the server.
Thanks to this module, only 4 lines are enough to run a static web server:
const app = require('express')();
const autostrada = require('autostrada')();
app.use(autostrada);
app.listen(80);
However, nothing prevents us from complicating things a little bit. For example, the following code associates file paths like /xxx/yyy/index.html
to the URLs /xxx/yyy/
and /xxx/yyy
. As well as the file paths like /xxx/yyy/zzz.html
to the URL /xxx/yyy/zzz
.
const app = require('express')();
const autostrada = require('autostrada')({
fromPathToUrl: path => {
if (path.match(/^((.*)\/)index\.html$/)) return [RegExp.$1, RegExp.$2];
if (path.match(/^(.*)\.html$/)) return RegExp.$1;
return path;
}
});
app.use(autostrada);
app.listen(80);
This is not the only option of the module, but for more details I invite you to visit the NPM page.