0

Folder structure of my express js app look like thisenter image description here

I am trying to load a modules folder which is located in root directory

routes/users.js

var express = require('express');
var router = express.Router();
var md=require('./modules');

/* GET users listing. */
router.get('/',function(req, res, next) {
  //res.send('respond with a resource');
  console.log('test');
  res.status(200).json({ error: 'message' });
});

module.exports = router;

But i am getting a module not found error:

Cannot find module './modules'

Note:

If modules folder is in node_modules folder require works fine,but getting module name error if its in project root directory, also an index.js file is present in modules folder

2 Answers 2

3

Module resolution in NodeJS is relative to the directory of your dependent module when your resolution starts with ..

In other words :

var module = require('../modules'); // Since your file is in `./routes/index` 
                                   // and `module` is in `./modules/index`

If you don't supply . in front of the required module, then NodeJS will look for that module in node_modules directory.

Excerpt from the documentation, which is self explanatory.

require(X) from module at path Y
1. If X is a core module,
   a. return the core module
   b. STOP
2. If X begins with './' or '/' or '../'
   a. LOAD_AS_FILE(Y + X)
   b. LOAD_AS_DIRECTORY(Y + X)
3. LOAD_NODE_MODULES(X, dirname(Y))
4. THROW "not found"

So in your case when you require('./modules'). NodeJS looks for it in the current directory ./routes, then since it can't find it, goes to look at it in node_modules.

Sign up to request clarification or add additional context in comments.

Comments

0

Instead of './modules' you can try require('../modules')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.