What is the node.js equivalent of window["myvar"] = value?
1 Answer
To set a global variable, use global instead of window.
global["myvar"] = value
8 Comments
ebohlman
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.Matrix
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.spex
@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. |