1

enter image description here

Above is the directory structure. I am trying to access the above highlighted file: DatabaseConnection using below code inside login_API.js

var connection = require("../../../../DatabaseConnection");

I am doing the same thing in many many other files.

Issue is: What will happen if the file path of DatabaseConnection is changes tomorrow. In that case I will have to rewrite the correct relative paths again in all the files.

Can you please suggest how can I change the above line of code to utilize it better?

I tried to follow an another way as mentioned here: https://stackoverflow.com/a/26163910/726802

But, failed to understand that how to use the below code in my case:

var myModule = require.main.require('./path/to/module');
1
  • If I understand correctly, require.main.require() cannot help you if the path of the required module is changed relatively to the root — it can help only if the path of the requiring module is changed. Commented Feb 24, 2019 at 23:53

2 Answers 2

1

You can place DatabaseConnection.js in node_modules and then require it this way:

var connection = require("DatabaseConnection");
Sign up to request clarification or add additional context in comments.

2 Comments

It is not safe to place this code in node_modules folder.
@Pankaj Maybe someone will be able to advise something else if you add some details in the question about why it is not safe to place the code in node_modules folder for your project.
0

With nodejs you can use __filename or __dirname. More information here, on the official site of Nodejs: https://nodejs.org/docs/latest/api/modules.html#modules_filename

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.