Easy way to include multiple route handler files in Express

·

3 min read

Purpose of this article

When you make backend server using Express, you usually write multiple files for route handlers. Every times you add new route file, you have to include that file in app.js like this app.use('/route', routeHandler);.

I will introduce easy way to include multiple route files without need for modifying app.js when you add new route handler files.

Basic way to add route handler in Express.

First, you write route handler files. For example, handler for user resources HTTP requests.

// file path: /routers/users.js

const express = require('express');
const router = express.Router(); 

router.get('/', function(req, res) {
  //..code for handling HTTP requests
});

module.exports = router;

The next step is adding user.js as a middleware of Express.

// file path: /app.js

const express = require('express');
const app = express();

const userRouter = require('./routers/users');
app.use('/users',usersRouter);

This approach is straightforward, but you have to modify app.js every times when you add new handler. This is not good for big applications with many handlers.

How to add handlers without modifying app.js

First, Make directory for route handlers. All route handler files should be placed in the directory.

Second, add some codes in app.js to include all handler files in the directory for handlers as middlewares of Express when you launch Express.

Let's see how to load all files

// file paht: /app.js

const express = require('express');
const app = express();
const fs = require('fs);

const addRouters = (routerPath, currentDepth, maxDepth) => {
    if(currentDepth > maxDepth) return;

    fs.readdirSync(routerPath).forEach((file)=>{
        const filePath = routerPath + '/' + file; 
        const stat = fs.stateSync(filePath);

        if(stat.isDirectory()){
            addRouters(filePath, currentDepth + 1, maxDepth);
        }else{   
            if(file.endWith('js'){
                const route = filePath.substring(1, filePath.length-3);
                app.use(route, require(filePath));
            }
        }
    });
}

addRouters('./routers', 0, 1);

addRouters function loads all files in ./routers with depth 1, and adds to Express. users.js and plants.js will be handlers for HTTP requests of /users and /plants respectively in the below structure.

| -- routers
|      |-- users.js
|      |-- plants.js
|      |-- lib
|            |-- validator.js
|
| -- app.js

With this way, you can add route handler files without modifying app.js.

Please let me know if there is anything wrong or better ways.