How to import a module that is in a different folder in Node.js?

Cordial greetings, I hope you are well.

I would like some guidance on how I can import a module that is in another folder.

Here is an image:
module_import

However when importing the module it generates me error:

Error: Cannot find module '../controllers/index.js'
Require stack:

I would be very grateful for your guidance.

1 thought on “How to import a module that is in a different folder in Node.js?”

  1. You need to understand, how path works. You are missing one more directory skip in your path.

    const module = require('../../controllers/index.js'); //as you are in route module, you need to go back to controller directory(so ../../path of file)
    

    For more details on path, you can check here.

    Reply

Leave a Comment