What is considered a good way to exchange global variables inside a node module?

How can I easily refer to other directories in my module without explicitly relative paths ( ../../../lib.. )?

I am writing a node module, and there are some global things that I want to reuse in my module.
Basically - I want to set the root path of the module as "global", so I can easily call other sources without using many relative paths ../../ and the like. This can cause messy code and can be easily mistaken or skipped if the design of the project changes.

So, I saw a lot of options in this post and some other libraries for working with such things (such as modules that enter the root path - app-module-path , rootpath , rfr , etc.), but they all refer to the base project / application, not the module used by others.

Setting up a global is a bad idea, and I realized that an environment variable is not such a good idea either.

Is there any good practice for this thing? Perhaps there is something I did not find or did not hear.

Here is an example of what I am trying to avoid and what I am looking for:

 // avoid things like that: // ./lib/something/forthat/doit.js var config = require('../../../config/project/type1/config.js'); // ./config/project/type1/config.js module.exports = { msg: 'hi' }; // find somethings like that: // when the root path/require can be found in every location of the module // and is relative to my app and not the app using my module. // ./lib/something/forthat/doit.js var config = require(rootPath + 'config/project/type1/config.js'); // OR var config = rootRequire('config/project/type1/config.js'); // OR anything else // ./config/project/type1/config.js module.exports = { msg: 'hi' }; 
+6
source share
2 answers

To get the current directory path, you can use the __dirname global variable anywhere in your nodejs project. Example: console.log(__dirname) write this to any file in your project, and the console will print the current directory path as a string. Or you can use the express session module, for example:

 var express = require('express'); var session = require('express-session'); var app = express(); app.use(session({myVar: 'abc'})); app.get('/',function(req,res){ var sess = req.session; console.log(sess); }); 
+1
source

First of all ..... relative paths do not create confusion at all. rather, you can call it messy (if you want), and this is considered best practice. But I can understand you too. That you don’t like very dirty codes. Therefore, for this situation, you should use this part / code of the code as static content. Therefore, you can easily access it by specifying the login path. But remember, this is an alternative to relative path tracing.

0
source

All Articles