Node.Js Global Variables

How to use global variable in node.js?

Most people advise against using global variables. If you want the same logger class in different modules you can do this

logger.js

  module.exports = new logger(customConfig);

foobar.js

  var logger = require('./logger');
logger('barfoo');

If you do want a global variable you can do:

global.logger = new logger(customConfig);

About global variables in Node.js

When a script is run, it is wrapped in a module. The top level variables in a script are inside a module function and are not global. This is how node.js loads and runs scripts whether specified on the initial command line or loaded with require().

Code run in the REPL is not wrapped in a module function.

If you want variables to be global, you assign them specifically to the global object and this will work in either a script or REPL.

 global.a = 1;

Global variables are generally frowned upon in node.js. Instead variables are shared between specific modules as needed by passing references to them via module exports, module constructors or other module methods.


When you load a module in node.js, the code for the module is inserted into a function wrapper like this:

(function (exports, require, module, __filename, __dirname) {
// Your module code injected here
});

So, if you declare a variable a at the top level of the module file, the code will end up being executed by node.js like this:

(function (exports, require, module, __filename, __dirname) {
var a = 1;
});

From that, you can see that the a variable is actually a local variable in the module function wrapper, not in the global scope so if you want it in the global scope, then you must assign it to the global object.

Node setInterval to modify global variable and access it from other module

Don't use a global. Though you may get it to work as you have discovered it is not easy to get it to work and is easy to forget something that causes your code to not work. It is also messing with node's internals and is deliberately working against the way node.js was designed. Node.js was explicitly designed to prevent people from using global variables. Therefore if you want to use global variables you need to somehow work around those protections.

Instead a simpler and more stable way to do this is to use a module.

One thing people don't realise about Commonjs modules is that they are singletons. This is a consequence of the module caching behavior. What this means is that if you import a module into 10 different files then you are not creating ten different objects that represent your module but all 10 files share a single object (the definition of the Singleton design pattern). Note that this works not only in node.js but also other Commonjs based systems like Webpack, React.js (jsx) and Typescript.

The code is really simple. So simple in fact that it makes no sense not to use this method because trying to circumvent the module system is far more complicated:

// shared.js

let shard_object = {
baseip: "http://10.***.**.**:8048/TESTDEV02/ODataV4/Company('****')"
}

module.exports = shared_object;

Note: You can of course write the above much simpler or much more complicated. I wrote it the way I did for clarity

Then you can share the module above with your other modules:

// getip.js

const shared = require('./shared');

var getip = function() {
var hosts = [["10.***.**.**", 8048]];
hosts.forEach(function (item) {
var sock = new net.Socket();
sock.setTimeout(2500);
sock
.on("connect", function () {
shared.baseip =
"http://'10.***.**.**':8048/TESTDEV02/ODataV4/Company('****')";
sock.destroy();
})
.on("error", function (e) {
shared.baseip =
"http://'10.***.**.**':8048/TESTDEV02/ODataV4/Company('****')";
})
.connect(item[1], item[0]);
})
}

module.exports = getip;

and it works as expected:

// main.js

const getip = require('./getip');
const shared = require('./shared');

setInterval(function(){
getip();
console(shared.baseip); // this gives the correct value
}, 4000);

How to declare in initialize global variable in TS-Node?

Step 1: Make TypeScript aware of your globals

The canonical way to define globals that exist both in Node.js and on the server is to use the var keyword.

declare global {
var __IS_DEVELOPMENT_BUILDING_MODE__: boolean;
var __IS_TESTING_BUILDING_MODE__: boolean;
var __IS_PRODUCTION_BUILDING_MORE__: boolean;
}

This makes them accessible via globalThis and by referencing them directly.

globalThis.__IS_DEVELOPMENT_BUILDING_MODE__;
__IS_DEVELOPMENT_BUILDING_MODE__;

Step 2: Define them on the client

That's what Webpack.DefinePlugin is already doing for you.

Step 3: Define them on the server

Find the entry point of your Node application and define the variable there.

var __IS_DEVELOPMENT_BUILDING_MODE__ = true;

A common practice is to use environment variables.

var __IS_DEVELOPMENT_BUILDING_MODE__ = process.env.NODE_ENV === 'development;

Global Variable NOT working - Node 14.15.3

I find this from Node documentation:

In browsers, the top-level scope is the global scope. This means that within the browser var something will define a new global variable. In Node.js this is different. The top-level scope is not the global scope; var something inside a Node.js module will be local to that module.

and Global object:

In JavaScript, there's always a global object defined. In a web browser, when scripts create global variables defined with the var keyword, they're created as members of the global object. (In Node.js this is not the case.)

It mean that when you declare var myVariable = 3; it doesn't go into the node global object, you can try to print global object out.

What is the 'global' object in NodeJS

While in browsers the global scope is the window object, in nodeJS the global scope of a module is the module itself, so when you define a variable in the global scope of your nodeJS module, it will be local to this module.

You can read more about it in the NodeJS documentation where it says:

global

<Object> The global namespace object.

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.js this is different. The top-level scope is
not the global scope; var something inside an Node.js module will be
local to that module.

And in your code when you write:

  • console.log(this) in an empty js file(module) it will print an empty object {} referring to your empty module.
  • console.log(this); inside a self invoking function, this will point to the global nodeJS scope object which contains all NodeJS common properties and methods such as require(), module, exports, console...
  • console.log(this) with strict mode inside a self invoking function it will print undefined as a self invoked function doesn't have a default local scope object in Strict mode.


Related Topics



Leave a reply



Submit