Hi Friends đź‘‹,

Welcome To Infinitbility ❤️!

Today, we will learn to export multiple files in a single file, for example, we have a lot of controller files in the node project but when I want to use any controller function then I don’t have to write also controller name.

Here, one more reason to do that way because in future when move one function to another controller then we haven’t worry about change imports also…

Let’s start today’s tutorial How to export multiple files in a single file in node js?

Now, we will create multiple sample controller files.

AuthController.js

const Login = () => {
    // ...
}

const Register = () => {
    // ...
}

module.exports = {
    Login,
    Register
}

We have to create one more controller

UserController.js

const ViewProfile = () => {
    // ...
}

const EditProfile = () => {
    // ...
}

module.exports = {
    ViewProfile,
    EditProfile
}

After that we have to create an index file behave of all controllers, here we will register all controllers.

And when we want to use any controller function we will use from the index file.

index.js

module.exports = {
    ...require("./AuthController"),    
    ...require("./UserController"),
}

Let’s see how we can use this file in the controller. Suppose, the following is our route file.

Route.js

const { Login } = require("../Controller/index");

Here, I just provide an example to export multiple files in a single.

I Hope, You will find a solution.

All the best đź‘Ť.