Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot find module (a custom module)

Tags:

node.js

I've following folder structure.

enter image description here

I am trying to access my custom module (core_programming/Constants.js) in other files.

I can access it in routes/index.js without any issue using following code.

var Constants = require('../core_programming/Constants.js');

But I am getting error when I try to access it inside core_programming/User.js with following statement.

var Constants = require('Constants.js');

It gives following error:

module.js:338
throw err;
^

Error: Cannot find module 'Constants.js'
    at Function.Module._resolveFilename (module.js:336:15)
    at Function.Module._load (module.js:286:25)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at Object.<anonymous> (D:\nodeJsProjects\AutomateBuild\core_programming\User.js:3:18)
    at Module._compile (module.js:434:26)
    at Object.Module._extensions..js (module.js:452:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
1 Oct 11:56:35 - [nodemon] app crashed - waiting for file changes before starting...

I've tried different ways for defining path in require like ../core_programming/Constants.js and ./core_programming/Constants.js but nothing works out.

What is the correct way for loading custom modules from the same directory.

And, I am on Windows if that helps.

like image 677
shashwat Avatar asked Mar 14 '23 15:03

shashwat


1 Answers

Try to use:

var Constants = require('./Constants.js');

This will force Node to figure out you are looking for a relative path and not a package in node_modules.

On a side note, windows paths use \, so consider trying it as well:

var Constants = require('.\Constants.js');
like image 196
Selfish Avatar answered Mar 24 '23 18:03

Selfish