Here, my question is, we use define function in php to define the contant globally but how can i achive same thing in nodejs
in php: define(nameofthecontant, value); in nodejs how to?
var dataBaseInfo = result.databaseInfo; // global.DB_HOST = dataBaseInfo['DB_HOST']; for(var keys in dataBaseInfo) { global.keys = dataBaseInfo[keys]; }
i have data in result.databaseInfo from database xml file and m trying to create global contant using for loop, its not working

- 1,001
- 1
- 8
- 9
-
Possible duplicate of [node.js global variables?](http://stackoverflow.com/questions/5447771/node-js-global-variables) – Dana Cartwright Oct 10 '16 at 17:30
-
Also, it should probably be `GLOBAL.keys = GLOBAL.keys || [];` then `GLOBAL.keys.push( dataBaseInfo[keys] )` – tmslnz Oct 10 '16 at 18:14
2 Answers
This is how you can define a variable in the global namespace:
global.nameofthecontant = value
This is something that you don't want to do in node.js though. Your question possibly is a duplicate of this question: node.js global variables?

- 1
- 1

- 3,045
- 1
- 17
- 30
-
yes, one more doubt i have, just i wll edit the question check it – Umakant Mane Oct 10 '16 at 13:31
Change your code from this:
global.keys = dataBaseInfo[keys];
to this:
global[keys] = dataBaseInfo[keys];
When you want to access or assign a property and the property name is in a variable, you use the obj[variableName]
syntax.
You could also use Object.assign here if you just want to copy a bunch of properties from one object to another:
Object.assign(global, databaseInfo);
As others have said, it is usually frowned upon to use globals in this way in node.js. Instead, you would typically expose these constants in a module and then just require in the module in any other module that wants to access the constants. This makes your code more modular and makes each module more self-contained.

- 683,504
- 96
- 985
- 979
-
its working but not what i was excepting, i wanted to use directly DB_HOST like constant , its working in single assignment explame: global.DB_HOST = localhost, once u assigned ln this way, then i can use it direclty, i need in looping to declare constant. is it possible? – Umakant Mane Oct 10 '16 at 17:06
-
@UmakantMane - You're going the wrong way for node.js development. Globals are evil. That is not how you should design code in node.js. Create a module with the globals in it, require in that constant and reference them as `someModule.someConstant`. Or, use destructing assignment to assign them from the module to local variables in your module which you can then use like globals, but they won't actually be evil globals. – jfriend00 Oct 10 '16 at 17:08
-
@UmakantMane - See what I added to my prior comment about destructing assignment as an option too. – jfriend00 Oct 10 '16 at 17:09