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');
vsemozhebuty
  • 12,992
  • 1
  • 26
  • 26
Pankaj
  • 9,749
  • 32
  • 139
  • 283
  • 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. – vsemozhebuty Feb 24 '19 at 23:53

2 Answers2

1

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

var connection = require("DatabaseConnection");
vsemozhebuty
  • 12,992
  • 1
  • 26
  • 26
  • 1
    It is not safe to place this code in node_modules folder. – Pankaj Feb 24 '19 at 23:42
  • @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. – vsemozhebuty Feb 24 '19 at 23:58
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

José Eras
  • 90
  • 4