Reputation: 13
I'm pretty new to node.js and I was wondering: seeing as the scope of any variable created is set to a sort of global scope, is there any way of listing out what variable names have already been initiated?
Upvotes: 1
Views: 53
Reputation: 707158
node.js variables are generally not global. The default is that any variable declared at the top level of a module is only in the module scope and does not conflict or interfere with any other modules.
Only variables explicitly assigned to the global
object are actually available globally.
global.myVar = "foo";
All others are contained within a smaller scope - module scope or a function scope within a module.
So, if you have a module like this:
var x = 3;
module.exports = function() {
return x;
}
Then, the variable x
is not a global variable at all. It is contained with the scope of this module. It would not conflict with a variable in any other module of the same name.
Because top level variables in a module are actually local variables within a module function wrapper and Javascript does not provide any means of iterating the local variables within a function scope, there is no way to iterate all top level variables within a module scope.
If you wanted to be able to iterate all variables in some context, then you can use a different format and put them as properties on an object.
var obj = {};
obj.x = 3;
obj.y = 5;
// list all enumerable properties of obj
for (var prop in obj) {
console.log("property: " + prop + " = ", + obj[prop]);
}
FYI, you can also use a debugger like node-inspector to view all variables declared within any given scope. You set a breakpoint in that scope and then look at the local variables present at that breakpoint.
Upvotes: 2