node.js无法在同一个文件夹中find模块
我试图使用一个简单的“颜色”模块来设置日志中的cli-colors,没有什么特别的。
那么,我有一个叫做colors.js
的模块,在path./app/config/colors.js
,内容是:
var clc = require('cli-color'); var colors = { ok: clc.cyan, error: clc.red.bold, warn: clc.yellowBright, high: clc.white.bgGreen }; module.exports = colors;
简单。 那么,当我需要它在server.js(在项目的根,在/应用程序的上方),它工作正常,但是,当我尝试使用它在./app/config/db.js
它抛出我一个错误:
Error: Cannot find module './app/config/colors.js' at Function.Module._resolveFilename (module.js:338:15) at Function.Module._load (module.js:280:25) at Module.require (module.js:364:17) at require (module.js:380:17) at Object.<anonymous> (/home/nano/Dev/bears-api/app/config/db.js:3:14) at Module._compile (module.js:456:26) at Object.Module._extensions..js (module.js:474:10) at Module.load (module.js:356:32) at Function.Module._load (module.js:312:12) at Module.require (module.js:364:17) 14 Sep 10:21:00 - [nodemon] app crashed - waiting for file changes before starting...
为什么如果它在server.js中工作?
您可能需要使用相对path的模块。
相对path根据需求模块的位置进行parsing。
引用文档
以“./”为前缀的模块与调用require()的文件相关。 也就是说,circle.js必须和require('./ circle')的foo.js在同一个目录下才能find它。
所以,如果你做了一个
var whatever = require('./app/config/colors.js');
在位于./app/config/
的模块中,那么节点将查找./app/config/app/config/colors.js
并失败。
如果需要和必需的模块都在同一个目录中,只需使用:
var whatever = require('./colors.js');
甚至更短:
var whatever = require('./colors');
该模块应该位于“node_modules”文件夹中,以便像您所描述的那样访问它。