我正在尝试加载位于根目录中的modules
文件夹
routes/user.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;
但我收到模块未找到错误:
Cannot find module './modules'
注意:
如果 modules
文件夹位于 node_modules
文件夹中,则 require 工作正常,但如果位于项目根目录中,则会出现模块名称错误,
modules
文件夹中还存在一个 index.js
文件
最佳答案
当你的解析以 .
开头时,NodeJS 中的模块解析是相对于你的依赖模块的目录的。
换句话说:
var module = require('../modules'); // Since your file is in `./routes/index`
// and `module` is in `./modules/index`
如果您没有在所需模块前面提供 .
,那么 NodeJS 将在 node_modules
目录中查找该模块。
摘自documentation ,这是不言自明的。
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"
因此,在您的情况下,当您 require('./modules')
时。 NodeJS在当前目录./routes
中查找,由于找不到,就去node_modules
中查找。
关于javascript - 自定义模块express js :Cannot find module name error when modules folder in root directory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40862494/