Delivering HTML files using Express can be useful when you need a solution for serving static pages.
js is a platform for building the i/o applications which are server-side event-driven and made using JavaScript. Express. js is a framework based on Node. js for which is used for building web-application using approaches and principles of Node.
NodeJS is an event-driven, non-blocking I/O model using JavaScript as its main language. It helps to build scalable network applications. Express is a minimal and flexible Node. js web application framework that provides a robust set of features for web and mobile applications.
You could use the static
middleware:
app.use("/", express.static(__dirname));
A server example:
var express = require('express');
var app = express();
app.use('/', express.static(__dirname + '/public'));
app.listen(3000, function() { console.log('listening')});
This is the file structure:
.
├── public
│ ├── a.html
│ ├── b.html
│ └── c.html
└── server.js
Documentation:
One idea would be to use a catch-all kind of route as the last route, like the following:
app.get('/:page', function(req, res) {
res.sendfile(path.join(__dirname, 'public', 'pages', path.basename(req.params.page) + '.html'));
});
That would require that you put your .html files into public/pages/about.html, etc.
You might want to switch the order of the static file router so that static files get precedence over routes, too, unless you want that route catching things in the public folder, like this:
app
app.set('view engine', 'ejs');
app.use(express.favicon("public/img/favicon.ico"));
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.static(path.join(__dirname, 'public')));
app.use(app.router);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With