Amandeep Kochhar

Feb 21, 2021

1 min read

[Node JS] — Auto Loading Routes with File System.

As our server has multiple API endpoints, our need for creating routes increases, along with increased demand of creating these routing files.

Traditionally, we were importing every single file that pertains to a specific route, to the root file as a middle ware. This can however be cumbersome if we have hundreds of routes.

To resolve this issue, let me show you a trick we can apply to auto-reload the express routes easily, so that you don't have to worry about importing them one by one in the root file of your Node JS application.

We can achieve it using the following line of code:

Mapping out all the files that are in our routes directory

In the above example what i am doing is requiring all the files i have created in the routes folder using an iteration.

Hopefully you liked this little trick, any improvement in this method is welcomed as comments.

A clap and a follow will encourage me to write more about my coding journey :)