简体   繁体   中英

Cannot find module (a custom module)

I've following folder structure.

在此处输入图片说明

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM