shammon shammon - 6 days ago 7
Node.js Question

Custom module express js:Cannot find module name error when modules folder in root directory

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

Answer

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.

Comments