I am trying to update the contents of a variable in nodejs with the use of a string. In client side javascript this was done with the use of window[variable] however since there is no "window" in nodejs. I tried using "this" and "module", however all im getting is an empty object. need help thanks
Code Snippet:
var myVariable = 'Hello';
var exchangeVariable = 'myVariable';
this[exchangeVariable] = 'Hello World';
/*
myVariable should equal to 'Hello World!'
*/
Thanks!
Here's some background before I answer your question directly:
In JavaScript, objects can be either indexed by the dot notation (someObj.property
) or by indexing them as you do in your example (someObj["property"]
)
In the browser, window
is the global context that the browser evaluates your code within. Node uses a variable called global
.
So, if you want to reference a variable you've defined globally:
> var someGlobalVar = "hi";
> var myLookupKey = "someGlobalVar";
> global[myLookupKey]
'hi'
However, this is generally considered very bad practice (in Node and the browser). There are a myriad of reasons for this, but I'm focusing on just one:
In Node, modules (each require
d file) should be treated as if they do not share global state (and in some cases, they cannot share state). I encourage you to read through the modules section of the node documentation if you are trying to share state across files.
You could create your own variables hash or array and assign the variable yourself.
var myVariable = "Hello";
var varArray = new Array()
varArray["exchangeVariable"] = myVariable;