Pankaj
Pankaj

Reputation: 10115

Relative path issue in node.js

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

Upvotes: 1

Views: 454

Answers (2)

José Eras
José Eras

Reputation: 90

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

Upvotes: 0

vsemozhebuty
vsemozhebuty

Reputation: 13822

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

var connection = require("DatabaseConnection");

Upvotes: 1

Related Questions