78

What is the node.js equivalent of window["myvar"] = value?

1 Answer 1

113

To set a global variable, use global instead of window.

global["myvar"] = value
Sign up to request clarification or add additional context in comments.

8 Comments

@Dokkat: window and global are just references to the global object in their respective environments. So you use them the same way in each environment. I updated my answer to show the code explicitly.
Note, however, that using Node's global should be done sparingly if at all. If there's some other way to share data between modules, use it instead. In particular, if you ever find yourself needing to use Cluster or some other way of distributing your app between processors, using global will break down because it won't be shared between the sub-processes.
not work ! var foo = 42; console.log(global.foo); //return undefined...
@spex: It works the same in node and the browser. In both cases, if you do var foo = 42 in the global environment, you'll be able to access foo as a property of the global object, which is window in the browser and global in NodeJS. However, if you do var foo = 42 in a module, you're not in the global environment; you're inside a function. Irrespective of this, the question isn't about using var to create a variable; it's about how to create a property directly on the global object.
@squint I understand, not sharing my own confusion but explaining why @Matrix is confused. He's not seeing window and global as equivalent in his specific case and so is saying they are wholly not equivalent.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.