Nodejs global variables

Node.js provides a special global object that provides access to global variables and functions that are accessible from each application module. An approximate analog of this object in javascript for the browser is the window. All available global objects can be found in the documentation.

For example, let’s create the following greeting.js module :

let currentDate = new Date();

global.date = currentDate;

module.exports.getMessage = function(){
    let hour = currentDate.getHours();
    if(hour >16)
        return "Good evening, " + global.name;
    else if(hour >10)
        return "Good afternoon, " + name;
    else
        return "Good morning, " + name;
}

Here, firstly, the global variable is set date:global.date = currentDate;

Secondly, in the module, we get the global variable name, which will be set from outside. At the same time, we can refer to the global variable name through the global: object global.name, or simply through the name, since the variable is global.

Let’s define the following application file app.js :

 
const greeting = require("./greeting");

global.name = "Eugene";

global.console.log(date);
console.log(greeting.getMessage());

Here we set the global variable name, which we get in the greeting.js module. And we also output the global variable date to the console. Moreover, all global functions and objects, for example, console are also available inside the global, so we can write both global.console.log(), and just console.log().

Let’s run the app.js file:

However, whenever possible, it is still recommended to avoid defining and using global variables, and preferentially focus on creating variables encapsulated within separate modules.