I've created a basic web app using Express, and provided a dynamic route such as:
app.get('/myroute/:user_id', function (req, res) {
res.render('mytemplate');
});
This renders the EJS template "mytemplate.ejs" when the user visits /myroute/15
Now, I'd also like to create a second route /staticroute that transmits a static HTML page somepage.html.
What's the best way to do this? Should these static pages be served outside of Express? I've seen some related answers on StackOverflow, but they either use deprecated functionality or they do not support cacheing.
There's res.sendfile() for such cases. Although if you don't need special routes for static files, you might look into using the express.static middleware instead.
Here's a quick solution you can try with memcached (too long to put into comments, I'd still recommend nginx's proxy_cache to avoid coding this below):
var Memcached = require('memcached'); // sudo apt-get install memcached
// npm install memcached
var memcached = new Memcached('localhost:11211'); // default
var ttl = 86400; // 24hrs time to live
function readContent(callback) { // async read with callback
fs.readFile("./someIndex.html", function (err, content) {
(err) ? callback(err) : callback(null, content);
})
}
app.get('/someRoutes', function (req, res) {
memcached.get('foo', function( err, content){ // get 'foo' from memcached
if( err ) console.error( err ); // .get() error handling
if( content ) { // data in memcached
// render content and output
} else { // data not in memcached
readContent(function (err, myFile) { // try reading file
if (myFile) { // file found, save to memcached & render
memcached.set('foo', myFile, ttl, function( err, data ){
if( err ) console.error( err ); // .set() error handling
});
// render myFile and output
}
}); // end readContent()
} // end if-content-else-
}); // end memcached.get()
}); // end app.get