15

Im trying to use a simple "colors" module to set cli-colors in my logs, nothing special.

Well, i have a module called colors.js in the path ./app/config/colors.js, the content:

var clc = require('cli-color');

var colors = {
  ok: clc.cyan,
  error: clc.red.bold,
  warn: clc.yellowBright,
  high: clc.white.bgGreen
};

module.exports = colors;

Simple. Well, when i require it in the server.js (at the root of the project, above of /app) it works fine, but, when i try to use it in the ./app/config/db.js it throws me an error:

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...

Why if it works in the server.js?

1
  • you have to show us the require that fails Commented Sep 14, 2014 at 15:26

2 Answers 2

28

You probably required the module using a relative path.

Relative paths are resolved in relation to the requiring module's location.

Quoting 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.

So if you did a

var whatever = require('./app/config/colors.js');

inside a module located in ./app/config/ then node will look for ./app/config/app/config/colors.js and fail.

If both requiring and required module are in the same directory just use:

var whatever = require('./colors.js');

or even shorter:

var whatever = require('./colors');
Sign up to request clarification or add additional context in comments.

Comments

-8

The module should be in the "node_modules" folder to access it like you have described.

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.