Search code examples
node.jsreadabilityclutter

How to manage NodeJs app code to reduce clutter


Hie,

I am developing a Nodejs (Express) web app and pretty much new to this technology. So far I see that there can only be one point of entry mine being my the server.js file. Now it seems all requests and/or processes should be initiated here which is fine for a smaller application, but my site has about 25 page routes already all of who's request should be handle here. I also have a dozen or so Ajax requests are handled here. Now even though I am processing different functions e.g CRUD operations in separate files, I still fear at some point my code will become unreadable as the server.js file get longer

const express = require("express")
const path = require("path")
const exphbs = require("express-handlebars")

let app = express()

app.set("views",path.join(__dirname,'templates'))
app.engine('handlebars',exphbs({defaultLayout:'main'}))
app.set('view engine','handlebars')

app.set('port',(process.env.PORT || 3000));

app.get('/',(req,res)=>{
    res.render('home',{'title':'Home'});
});
app.get('/home',(req,res)=>{
    res.render('home',{'title':'Home'});
});
app.get('/register',(req,res)=>{
    res.render('register',{'title':'Register'});
});
app.use(express.static(path.join(__dirname, '/public')));

app.listen(app.get('port'),()=>{
    console.log(`Server started on port : ${app.get('port')}`)
})

So far my server.js is this small, but it just hit me that I have 25 pages and multiple Ajax processes on each.


Solution

  • Yes, you have to structure your routes. For that, you have to look at Express Router. You have to create different route files based on a specific resource.

    /routes/homeRoutes.js

    const express = require("express");
    const router = express.Router();
    router.get('/',(req,res)=>{
           res.render('home',{'title':'Home'});
    });
    
    module.exports = router;
    

    server.js

    const homeRoutes = require("./routes/homeRoutes");
    app.use("/api/v1/home", homeRoutes);
    

    Also, have a look at the following links for a better understanding of project structure and express router.