How to share variables in nodejs? - node.js

I want to share variables between different files in node.
I have seen many sites but none of them worked for me.
these are some of the sites
Share variables between files in Node.js?
https://stackabuse.com/how-to-use-module-exports-in-node-js/
usersConroller.js file
module.exports.fetchedUser = fetchedUser;
module.exports.fetchedUser.branchId = branchId;
module.exports.fetchedUser.role = role;
module.exports.isLoggedIn = isLoggedIn;
then on another file
I imported userController and tried to access the variables
as this
let usersController = require('./usersController');
let fetchedUser = usersController.fetchedUser;
let branchId = usersController.branchId;
let role = usersController.role;
let isLoggedIn = usersController.isLoggedIn;
and when i console.log() the variables, is says undefined
any help.please??
Thank You for your help!!

If there is no typo anywhere and you are using correct file name in your require statement, then the problem is your way of accessing the variables.
Your export variable looks something like this
exports = {
fetchedUser: {
branchId: <some_value>,
role: <some_other_value>
},
isLoggedIn: <another_value>
}
Now, let's look at your code:
// this line should give you the desired result
let fetchedUser = usersController.fetchedUser;
// this a wrong way to access branchId
// let branchId = usersController.branchId;
// branchId is actually a property of fetchedUser
// so you'll have to first access that
let branchId = usersController.fetchedUser.branchId;
// alternatively (because fetchedUser is already
// saved in a variable):
branchId = fetchedUser.branchId;
// similar problem while accessing role property
// let role = usersController.role;
// correct way:
let role = fetchedUser.role;
// this line is correct
let isLoggedIn = usersController.isLoggedIn;

Related

Compact way to assign nested property to root of a new object

I'm wondering if there's a compact way to pull a property from an object, and then assign said property to the root of a new object, using the same property name.
Basically, I'd like to do the following without needing the first line:
const targetProp = someObj.data.targetProp;
const newObj = {
targetProp
}
What I'd imagine it might look like:
const newObj = {
[someObj.data.targetProp]
}
Where newObj would then have a property named 'targetProp', with the value of someObj.data.targetProp
There's no need for an extra variable:
const newObj = {
targetProp: someObj.data.targetProp
}
Destructuring is an option, which will reduce the size of the original code, but that requires keeping a first line:
const { targetProp } = someObj.data;
const newObj = { targetProp };
I don't think there's anything better than these two options.

How to update a module.exports properly?

I have this file that stores some of my environment variables.
Let's call it generalEnv.js
module.exports = {
CONSTANT_1: process.env.CONSTANT_1,
CONSTANT_2: process.env.CONSTANT_2
};
When the app initializes, I don't put the value of process.env.CONSTANT_1 in the env variables yet because I have to look into some places first if it exists(mongodb for instance). If it does not exists on mongodb, I will add a value into process.env.CONSTANT_1 and I was expecting that the value will reflect on generalEnv now.
When I tried accessing the CONSTANT_1 in another file.
Let's call it getConstantOne.js
const { CONSTANT_1 } = require('./generalEnv');
module.exports = () => {
// I was expecting that CONSTANT_1 will have a value here now
if(!CONSTANT_1) {
// do something
}
return CONSTANT_1
}
it does not reflect.. how do I update the closure of generalEnv.js for process.env.CONSTANT_1 to reflect on CONSTANT_1?
When assigning to a variable (or a value in an object/element in an array), the assignment will replace the value, not modify it. Therefore, any "copies" of that value will not be affected, and remain the same. Consider this example:
let a = 0;
let b = a;
a = 1;
What happens to b? Answer: Its value is 0.
To work around this we need some way of modifying the value instead of replacing it. Unfortunately, "primitive types" (strings/numbers/booleans etc.) cannot be modified in javascript. There are types that can be modified however, such as objects. You could solve this by wrapping your variables in an object called "env".
let env: {
CONSTANT_1: process.env.CONSTANT_1,
CONSTANT_2: process.env.CONSTANT_2
}
modules.exports = { env }
and then to modify:
env.CONSTANT_1 = "new value"
and to access:
if (!env.CONSTANT_1) { ... }

Revert variables inside a Loop in Node JS

I am trying one logic in Node JS code which looks something like below:-
var startPersons1 = JSON.parse(JSON.stringify(persons1));
var startPersons2 = JSON.parse(JSON.stringify(persons2));
var startPersons3 = JSON.parse(JSON.stringify(persons3));
var startPersons4 = JSON.parse(JSON.stringify(persons4));
.....
// Operations on persons1, persons2, persons3, persons4 which are changed in methods called here
....
// Now persons1, persons2, persons3, persons4 are modified
// Now, if I wanted persons1, persons2, persons3, persons4 to come to their original state above, ie.
// startPersons1, startPersons2, startPersons3, startPersons4, I am doing something like this
persons1 = JSON.parse(JSON.stringify(startPersons1));
persons2 = JSON.parse(JSON.stringify(startPersons2));
persons3 = JSON.parse(JSON.stringify(startPersons3));
persons4 = JSON.parse(JSON.stringify(startPersons4));
You can assume this is inside some for loop.
So, is there a better way to do this revert everytime. The number of variables can increase by lot.
if persons1, persons2 etc are inside an array, you could use map function
var persons = [/*array of persons*/]
var newpersons = persons.map(function(person) {
/*change here your person object and return it.*/
return person
})
/*here persons is the originalone, newpersone is the new version*/

How to access variables in NodeJS

I would like to understand best practice for accessing variables that are defined in an external module that would then be required in several other files.
Say we have the two following files, I would like to access the value of the h variable in consume.js
//central.js
module.exports = {
common: function() {
var h = "hello";
var b = "enabled"
}
};
and
//consume.js
var g = require('./central');
//get the value of variable h from central.js
Taking this a step further, if I have the following consume.js, fetch.js and get.js files that all imported central.js, and required a common set of variables from central.js, how does one go about defining these common variables inside central.js so that the dependent files can consume them?
Thanks!
Export:
// central.js
module.exports = {
h: "hello",
b: "enabled"
}
Import:
// consume.js
const { h, b } = require('./central')
Or alternatively:
// get.js
const central = require('./central')
// central.h
// central.b
Hope this helps!

How to use dot(.) to MongoDB(Mongoose) schema as a parameter [duplicate]

It's difficult to explain the case by words, let me give an example:
var myObj = {
'name': 'Umut',
'age' : 34
};
var prop = 'name';
var value = 'Onur';
myObj[name] = value; // This does not work
eval('myObj.' + name) = value; //Bad coding ;)
How can I set a variable property with variable value in a JavaScript object?
myObj[prop] = value;
That should work. You mixed up the name of the variable and its value. But indexing an object with strings to get at its properties works fine in JavaScript.
myObj.name=value
or
myObj['name']=value (Quotes are required)
Both of these are interchangeable.
Edit: I'm guessing you meant myObj[prop] = value, instead of myObj[name] = value. Second syntax works fine: http://jsfiddle.net/waitinforatrain/dNjvb/1/
You can get the property the same way as you set it.
foo = {
bar: "value"
}
You set the value
foo["bar"] = "baz";
To get the value
foo["bar"]
will return "baz".
You could also create something that would be similar to a value object (vo);
SomeModelClassNameVO.js;
function SomeModelClassNameVO(name,id) {
this.name = name;
this.id = id;
}
Than you can just do;
var someModelClassNameVO = new someModelClassNameVO('name',1);
console.log(someModelClassNameVO.name);
simple as this
myObj.name = value;
When you create an object myObj as you have, think of it more like a dictionary. In this case, it has two keys, name, and age.
You can access these dictionaries in two ways:
Like an array (e.g. myObj[name]); or
Like a property (e.g. myObj.name); do note that some properties are reserved, so the first method is preferred.
You should be able to access it as a property without any problems. However, to access it as an array, you'll need to treat the key like a string.
myObj["name"]
Otherwise, javascript will assume that name is a variable, and since you haven't created a variable called name, it won't be able to access the key you're expecting.
You could do the following:
var currentObj = {
name: 'Umut',
age : 34
};
var newValues = {
name: 'Onur',
}
Option 1:
currentObj = Object.assign(currentObj, newValues);
Option 2:
currentObj = {...currentObj, ...newValues};
Option 3:
Object.keys(newValues).forEach(key => {
currentObj[key] = newValues[key];
});

Resources