I am doing a website for an association and I have never done the server side before. Here I made a very simple routing system:
app.set('port',(process.env.PORT || 5000));
app.use(express.static(__dirname + '/public' ));
app.use(express.static(__dirname + '/views' ));
app.get('/',function(req,res,next) {
res.redirect('/en/insa');
})
.get('/:language/:page?',function(req, res, next){
var path = __dirname+'/views/'+req.params.language+'/'+req.params.page+'.ejs';
fs.access(path,function(err) {
if (err) {
res.status(404);
console.error('404 : /' + req.params.page);
res.render('404.ejs', {
page: req.params.page
});
return;
}
res.charset = "utf-8";
res.render(path ,{language: req.params.language});
});
})
.listen(app.get('port'),function() {
console.log('Server is running, server is listening on port ',app.get('port'));
})
I just redirect automatically the client if he hits the main www.site.com/ page and then I just check for the language and page in the URL like www.site.com/en/description for instance. The fs.access
function checks if the EJS (that's a template generator for HTML pages) page actually exists in the folder before rendering it.
Is there anything that could go wrong with this code, or something that could be done better?