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?
To fix the Cannot find module error, simply install the missing modules using npm . This will install the project's dependencies into your project so that you can use them. Sometimes, this might still not resolve it for you. In this case, you'll want to just delete your node_modules folder and lock file ( package-lock.
To solve the "Cannot find module path or its corresponding type declarations" error, install the types for node by running the command npm i -D @types/node . You can then import path with the following line of code import * as path from 'path' .
If you have run the npm install command before, then it's possible that the installation of the module is incomplete or corrupted. Delete the node_modules/ folder using the rm -rf node_modules command, then run npm install again. That may fix the issue.
To fix Cannot find module errors, install the modules properly by running a npm install command in the appropriate directory as your project's app. js or index. js file. or delete the node_modules folder and package-lock.
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With