Reputation: 5081
In browser-based JavaScript, you can do something like this:
var foo = "foo";
(function() {
var foo = "bar";
console.log(foo);
// => "bar"
console.log(window["foo"]);
// => "foo"
})();
Is there any way to do something similar in Node, which lacks a window
object?
Upvotes: 3
Views: 2724
Reputation: 143017
If you want an environment agnostic approach, for example, when writing code to work on both the browser and Node.js, you can do something like this in global code at the top of your JavaScript file:
var globalObject = typeof global === "undefined" ? this : global;
and then use globalObject
similar to how you would window
in the browser context and as you would use global
in the Node.js context.
Note that you must declare a variable without var
for it to be part of the global
object in Node.js.
Upvotes: 1
Reputation: 25882
You can access global variables using global
keyword in nodejs.
Note:- There is one rule in nodejs
only those variables willl be global variables which dose not have declared using var
.
Like if you have declareation like bellow
foo = "sample"; //this you can access using global
But
var foo = "sample"; //this you cann't access using global.
The second one is not actually in global scope, it's local to that module.
From node global docs
In browsers, the top-level scope is the global scope. That means that in browsers if you're in the global scope var something will define a global variable. In Node this is different. The top-level scope is not the global scope; var something inside a Node module will be local to that module.
Upvotes: 1