How to structure a express.js application?

前端 未结 4 2021
南旧
南旧 2020-11-30 16:28

Is there a common convention for breaking up and modularizing the app.js file in an Express.js application? Or is it common to keep everything in a sin

4条回答
  •  情书的邮戳
    2020-11-30 17:02

    I have my apps build on top of the express-generator tool. You can install it by running npm install express-generator -g and run it using express .

    To give you a perspective, one of my smaller application's structure looked like this:

    ~/
    |~bin
    | |-www
    |
    |~config
    | |-config.json
    |
    |~database
    | |-database.js
    |
    |~middlewares
    | |-authentication.js
    | |-logger.js
    |
    |~models
    | |-Bank.js
    | |-User.js
    |
    |~routes
    | |-index.js
    | |-banks.js
    | |-users.js
    |
    |~utilities
    | |-fiat-converersion.js
    |
    |-app.js
    |-package.json
    |-package-lock.json
    

    One cool thing I like about this structure I end up adopting for any express application I develop is the way the routes are organized. I did not like having to require each route files into the app.js and app.use() each route, especially as the file gets bigger. As such, I found it helpful to group and centralize all my app.use() on a ./routes/index.js file.

    In the end, my app.js will look something like this:

    ...
    const express = require('express');
    const app = express();
    
    ...
    require('./routes/index')(app);
    

    and my ./routes/index.js will look something like this:

    module.exports = (app) => {
      app.use('/users', require('./users'));
      app.use('/banks', require('./banks'));
    };
    

    I am able to simply require(./users) because I wrote the users route using express.Router() which allows me to "group" multiple routes and then export them at once, with the goal of making the application more modular.

    This is an example of what you would fine on my ./routers/users.js route:

    
    const router = require('express').Router();
    
    router.post('/signup', async (req, res) => {
        // Signup code here
    });
    
    module.exports = router;
    

    Hopefully this helped answer your question! Best of luck!

提交回复
热议问题