我正在尝试使用一个简单的“颜色”模块在我的日志中设置 cli-colors,没什么特别的。
嗯,我在路径./app/config/colors.js
中有一个叫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 上方)它工作正常,但是,当我尝试在 ./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 中工作,为什么?
最佳答案
您可能需要使用相对路径的模块。
相对路径根据需要模块的位置进行解析。
引用 docs
A module prefixed with './' is relative to the file calling require(). That is, circle.js must be in the same directory as foo.js for require('./circle') to find it.
所以如果你做了一个
var whatever = require('./app/config/colors.js');
在位于 ./app/config/
的模块中, Node 将查找 ./app/config/app/config/colors.js
并失败。
如果需要和需要的模块都在同一个目录中,只需使用:
var whatever = require('./colors.js');
甚至更短:
var whatever = require('./colors');
关于node.js 在同一文件夹中找不到模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25834836/