Search code examples
javascriptnode.jsbackendecma

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: enter image description here

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.


Solution

  • 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.