Nano
Nano

Reputation: 847

node.js cannot find a module in the same folder

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?

Upvotes: 15

Views: 22685

Answers (2)

Nedelin Yordanov
Nedelin Yordanov

Reputation: 149

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

Upvotes: -8

soulcheck
soulcheck

Reputation: 36777

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');

Upvotes: 28

Related Questions